htmlTable producing row numbers - r

I'm putting a table into an RMarkdown presentation and it is producing erroneous row numbers in the output I've got this:
library(htmlTable)
d <- data.frame(
x=c('1','2','3'),
y=c('A','B','C')
)
htmlTable(d)
How do I remove these?

Set rnames equals to FALSE.
---
title: "htmlTable"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(htmlTable)
d <- data.frame(
x=c('1','2','3'),
y=c('A','B','C')
)
htmlTable(d, rnames = FALSE)
```

library("xtable")
d <- data.frame(
x=c('1','2','3'),
y=c('A','B','C')
)
print(xtable(d), type="html", include.rownames = FALSE)

Related

Markdown - call a result from a table or a list in the text

Here is an example of what I'm trying to do. I would like to call in the text a result from a table itself coming from a random computation.
---
title: "RĂ©gression logistique"
subtitle: "Analyse quantitative II"
author:
- name: ""
- affiliation:
date: "TP 4"
output:
html_document:
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r message=FALSE}
bystander <- data.frame(reaction = c(rep(0, 30), rep(1, 30)),
age.victime = c(rep(5, 5),rep(85, 5),rep(7, 5),rep(35, 5),rep(45, 5),rep(50, 5)),
sexe.victime = c(rep(0, 20), rep(1, 10), rep(0, 10), rep(1, 20)),
nbrpers = c(11:40, 0:29),
statutse = c(rep(4, 30), rep(18, 30)))
#install.packages("caret")
library(caret)
# install.packages("lmtest")
library(lmtest)
#install.packages("pscl")
library(pscl)
#install.packages("e1071")
library(e1071)
```
```{r}
Train <- createDataPartition(bystander$reaction, p=0.8, list=FALSE)
training <- bystander[ Train, ]
testing <- bystander[ -Train, ]
training$reaction <- as.factor (training$reaction)
model_fit <- train(reaction ~ age.victime + sexe.victime + nbrepers + statutse, data=training, method="glm")
testing$reaction <- as.factor (testing$reaction)
pred <- predict(model_fit, newdata=testing)
confusionMatrix(data=pred, testing$reaction)
```
We obtain a an accuracy of `r confusionMatrix(data=pred, testing$reaction)`.
I just want the Accuracy from the overall in the confusionMatrix. Is there a way to call only this result because my trial is not working there (pretty logical, it's a list), like in latex when you can reference your results and call it later.
Thank's in advance!
To achieve your desired result assign the result of calling caret::confusionMatrix to variable. Afterwards you could access the Accuracy in an inline chunk like so:
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(caret)
```
```{r}
conf_mat <- caret::confusionMatrix(iris$Species, sample(iris$Species))
```
We obtain an accuracy of `r conf_mat$overall[["Accuracy"]]`.

Table rendering in pdf document using R markdown

After days trying to find a solution, I give up and ask for help.
I decided to use R Markdown very recently. While I can render plots as I want, I cannot succeed in rendering my tables in a pdf doc properly.
Here the corresponding [EDITED]code:
---
title: "My_title"
output:
pdf_document: default
html_document:
df_print: paged
params:
date: "!r Sys.Date()"
---
```{r library, echo=F, message=F, warning=F, paged.print=FALSE}
suppressMessages(library("knitr"))
suppressMessages(library(reshape2))
suppressMessages(library(splines))
suppressMessages(library(kableExtra))
suppressMessages(library(gplots))
```
```{r, setup, echo = F}
opts_knit$set(root.dir = "my_path")
knitr::opts_chunk$set(echo = F)
```
```{r}
dt <- expand.grid(Region=c("a","b","c"), Country=c("d","e","f"), Cancer= c("All", "CRC", "Breast"),
age.1.1=1:2,
age.1.2=1:2,
age.1.3=1:2)
```
```{r Table_1, INCLUDE = TRUE}
cancer.lab <- c("All", "CRC", "Breast")
for (i in 1:3){
b <- dt[dt$Cancer==cancer.lab[i],]
b <- b[,-3]
t <- kable(b, format = ,caption = "Fig", row.names = F) %>%
kable_paper() %>%
kable_styling(font_size = 9) %>%
add_header_above(c(" " = 2, "1998" = 3))
print(t)
}
```
Again I am new and I surely miss something.
I use Mac if it may explain something.
Thank you for your help.
Sophie.
I think this is the same issue as dealt with here: https://stackoverflow.com/a/53632154/2554330. The problem is that you need to use knit_print to print the tables, but you can't do that in a loop.
So if you change the last code chunk to this, it should work:
```{r Table_1, INCLUDE = TRUE}
results <- c()
cancer.lab <- c("All", "CRC", "Breast")
for (i in 1:3){
b <- dt[dt$Cancer==cancer.lab[i],]
b <- b[,-3]
t <- kable(b, format = ,caption = "Fig", row.names = F) %>%
kable_paper() %>%
kable_styling(font_size = 9) %>%
add_header_above(c(" " = 2, "1998" = 3))
results <- c(results, knit_print(t))
}
asis_output(results)
```

latex kable side-by-side tables "Not in outer par mode"

I am trying to create a page with side-by-side tables. I used other SO answers to do this for a simple table
```{r start-block, include=F,echo=F}
library(dplyr)
library(knitr)
library(kableExtra)
```
```{r sample, echo=FALSE, results='asis'}
t1 <- kable(head(mtcars)[1:3], format = "latex", booktabs = TRUE) %>% kable_styling(latex_options = c("striped"), font_size=5)
t2 <- kable(head(mtcars)[4:6], format = "latex", booktabs = TRUE) %>% kable_styling(latex_options = c("striped"), font_size=5)
cat("\n")
cat("\\newpage")
cat("\\begin{table}[!htb]")
cat(c("\\begin{minipage}{.5\\linewidth}
\\caption{}
\\centering",
t1,
"\\end{minipage}%
\\begin{minipage}{.5\\linewidth}
\\centering
\\caption{}",
t2,
"\\end{minipage}") )
cat("\\end{table}")
```
I am trying to reproduce the same behavior with a custom table (.RDS format file: tbl). This works fine without side-by-side tables.
```{r table, echo=FALSE, results='asis'}
tbl <- readRDS("table.RDS") #load file using the link "tbl"
cat(tbl)
```
byt I am getting an error when I try this table side-by-side.
```{r table2, echo=FALSE, results='asis'}
cat("\n")
cat("\\newpage")
cat("\\begin{table}[!htb]")
cat(c("\\begin{minipage}{.5\\linewidth}
\\caption{}
\\centering",
tbl,
"\\end{minipage}%
\\begin{minipage}{.5\\linewidth}
\\centering
\\caption{}",
tbl,
"\\end{minipage}") )
cat("\\end{table}")
```
! LaTeX Error: Not in outer par mode.
I would recommend using the LaTeX package subcaption for building the side-by-side tables/figures.
An example .Rmd file:
---
title: "Answer for SO Question 50879745"
header-includes:
\usepackage{subcaption}
\usepackage{booktabs}
\usepackage[table]{xcolor}
---
```{r start-block}
library(dplyr)
library(knitr)
library(kableExtra)
opts_chunk$set(echo = FALSE)
```
Build two example tables based on the `mtcars` data set.
```{r sample, results='asis'}
t1 <- kable(head(mtcars)[1:3], format = "latex", booktabs = TRUE) %>% kable_styling(latex_options = c("striped"), font_size=5)
t2 <- kable(head(mtcars)[4:6], format = "latex", booktabs = TRUE) %>% kable_styling(latex_options = c("striped"), font_size=5)
```
Modify the tables to use the `subtable` environment and added labels and
captions.
```{r}
t1 <- gsub("\\begin{table}[H]", "\\begin{subtable}[b]{0.48\\linewidth}\n\\caption{\\label{tab:1a}This is Table 1 in the example, but now labeled with a (a).}\n", t1, fixed = TRUE)
t1 <- gsub("\\end{table}", "\\end{subtable}", t1, fixed = TRUE)
t2 <- gsub("\\begin{table}[H]", "\\begin{subtable}[b]{0.48\\linewidth}\n\\caption{\\label{tab:1b}Shorter caption.}", t2, fixed = TRUE)
t2 <- gsub("\\end{table}", "\\end{subtable}", t2, fixed = TRUE)
```
Place the tables into the document.
```{r, results = "asis"}
cat("",
"\\begin{table}[!htb]",
"\\centering",
"\\caption{\\label{tab:tab1}Two tables, side-by-side.}",
t1,
t2,
"\\end{table}",
"",
sep = "\n")
```
Another example, start by reading in a rds file.
```{r table, results = "asis"}
tbl <- readRDS("table.RDS") #load file using the link "tbl"
cat(tbl)
```
A few modifications to Table~\ref{tab:comments-block} will be made so that we
can show the table twice in a `subtable`.
```{r table2_mod}
tbl <- gsub("\\begin{table}", "\\begin{subtable}[t]{0.48\\linewidth}", tbl, fixed = TRUE)
tbl <- gsub("\\end{table}", "\\end{subtable}", tbl, fixed = TRUE)
```
Printing the tables works, see \ref{tab:tab3}, but there is overlap as the
tables are too wide. Consider the `tabularx` package as a solution or an ad hoc
approach of changing the font size.
```{r, results = "asis"}
cat("",
"\\begin{table}[!htb]",
"\\centering",
"\\caption{\\label{tab:tab3}Two tables, side-by-side.}",
# "\\scriptsize",
tbl,
tbl,
"\\end{table}",
# "\\normalsize",
"",
sep = "\n")
```
Which turned into this pdf:
The files and graphics for this example can be found here: https://github.com/dewittpe/so/tree/master/50879745

Group only some columns in LaTeX table using R

I am trying to create a table in RMarkdown that looks similar to the following example:
---
title: "Example"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r cars, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
library(Hmisc)
latex(mtcars, file = "", cgroup = c("mpg", "cyl"), n.cgroup = c(1,10))
```
I would like to group columns 2 through 10. Any ideas on how I can accomplish this with the Hmisc package or any other R package?
I think just using a blank header name for the first column gives you what you want:
latex(mtcars, file = "", cgroup = c("", "cyl"), n.cgroup = c(1,10))
Result:
Using my package:
library(huxtable)
hux_cars <- as_hux(mtcars, add_colnames = TRUE)
hux_cars <- insert_row(hux_cars, c('mtcars', 'cyl', rep('', 9)))
colspan(hux_cars)[1, 2] <- 10
align(hux_cars)[1, 2] <- 'centre'
bold(hux_cars)[1, ] <- TRUE
position(hux_cars) <- 'left'
quick_pdf(hux_cars)
Which produces:

Why does datatable not print when looping in rmarkdown?

I am working on creating a dynamic rmarkdown document. The end result should create a tab for each 'classification' in the data. Each tab should have a datatable, from the DT package, with the data printed to it. Below is the code I have been using:
---
output: html_document
---
# Setup{.tabset}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(DT)
```
```{r data.setup}
set.seed = 1242
rows = 64
data.1 = runif(rows, 25, 75)
data.2 = runif(rows, .01, 1)
data.3 = runif(rows, 1, 10)
classification = c("A", "B", "C", "D")
df = data.frame(cbind(data.1 = data.1, data.2 = data.2, data.3 = data.3, classification = classification))
df$data.1 = as.numeric(df$data.1)
df$data.2 = as.numeric(df$data.2)
df$data.3 = as.numeric(df$data.3)
```
```{r results= 'asis'}
for(j in levels(df$classification)){
df.j = df[df$classification == j, ]
cat(paste("\n\n## Classification: ", j, "##\n"))
w = datatable(df.j)
#datatable(df.j)
print(w)
}
```
Notice I have commented out straight calls to the datatable function, those were not printing to rmarkdown. The results of the call as written generate an html document with the correct tabs, but no datatables in them. Additionally, the datatables actually display in my RStudio session with the correct subsetting. As a test, I tried achieving the goal using the kable function from knitr, and the tables were printed in their appropriate tabs, unfortunately, kable does not have all the functionality required.
This is not a complete answer as some of this is still puzzling me, but at least this is good enough to get you going while I try to understand some more.
---
output: html_document
---
# Setup{.tabset}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(DT)
```
```{r data.setup}
set.seed <- 1242
rows <- 64
data.1 <- runif(rows, 25, 75)
data.2 <- runif(rows, .01, 1)
data.3 <- runif(rows, 1, 10)
classification <- c("A", "B", "C", "D")
df <- data.frame(cbind(data.1 = data.1, data.2 = data.2, data.3 = data.3, classification = classification))
df$data.1 <- as.numeric(df$data.1)
df$data.2 <- as.numeric(df$data.2)
df$data.3 <- as.numeric(df$data.3)
```
```{r include = FALSE}
# Why, oh why do I need this chunk?
datatable(df)
```
```{r results = 'asis'}
for(j in unique(df$classification)){ # You were using level() here, so your for-loop never got off the ground
df.j <- df[df$classification == j, ]
cat(paste("\n\n## Classification: ", j, "##\n"))
print( htmltools::tagList(datatable(df.j)) )
}
The third chunk is required for this to work, I'm not yet sure why.
Reaching here by googling the same question. This has worked for me: https://gist.github.com/ReportMort/9ccb544a337fd1778179.
Basically, generate a list of rendered tibbles and manually call knit.
Here is a working Rmd based on your example, using the technique found in the above link:
---
output: html_document
---
# Setup{.tabset}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(DT)
```
```{r data.setup}
set.seed <- 1242
rows <- 64
data.1 <- runif(rows, 25, 75)
data.2 <- runif(rows, .01, 1)
data.3 <- runif(rows, 1, 10)
classification <- c("A", "B", "C", "D")
df <- data.frame(cbind(data.1 = data.1, data.2 = data.2, data.3 = data.3, classification = classification))
df$data.1 <- as.numeric(df$data.1)
df$data.2 <- as.numeric(df$data.2)
df$data.3 <- as.numeric(df$data.3)
```
```{r include = FALSE}
# prepare a list of 4 sub-dataframes, each corresponding to one classification
df_list <- split(df, df$classification)
```
```{r create-markdown-chunks-dynamically, include=FALSE}
out = NULL
for (c in names(df_list)) {
knit_expanded <- paste0("\n\n## Classification: ", c, "##\n\n```{r results='asis', echo=FALSE}\n\ndatatable(df_list[['", c, "']])\n\n```")
out = c(out, knit_expanded)
}
```
<!--- knit those table chunk statements -->
`r paste(knit(text = out), collapse = '\n')`

Resources