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

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

Related

htmlTable producing row numbers

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)

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)
```

Rmarkdown knitr problem with £ pound sterling symbol not displaying correctly

When I include the £ sterling symbol in text when using knitr and kableExtra this displays as <U+00A3> in the output.
Is there any way I can get £ symbol to display with kableExtra and knitr?
I am using R 3.6.0 and package versions knitr_1.29 and kableExtra_1.1.0.
Example code below:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE)
library(rmarkdown)
library(knitr)
library(tidyverse)
library(kableExtra)
library(xtable)
```{r make a table, results='asis'}
# input metric
MI_input1 <- data.frame(cbind(c("£15.5m",""),c("£32.3m","157%"),c("","")))
# create MI table
MI_table1 <- kableExtra::kable(MI_input1, col.names = NULL, align = "c") %>%
kable_styling("bordered", full_width = F) %>%
pack_rows("Value in £", 1, 2, label_row_css = "text-align: center") %>%
column_spec(1:3, width = "1.5cm") %>%
row_spec(1:2, align = "c")
MI_table1

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:

R kableExtra latex: Add linebreaks to rotated header row

I'm trying to produce table to a Latex-pdf document. I'm using kableExtra and knitr in R.
I have a table that has long column names. When I rotate the header row by 90 degrees linebreaks won't work. Does anyone have an idea how I could achieve both rotated row and linebreaks?
My example is the same as in Hao's Best Practice for newline in Latex table, but I added piped row_spec to the end of the code.
\documentclass[10pt,a4paper]{article}
\usepackage[table]{xcolor}
\begin{document}
\begin{table}
<<global_options, echo=FALSE>>=
library(kableExtra)
library("dplyr")
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
dt_lb %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F,
col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"))) %>%
row_spec(0, angle = 90, align='l', monospace=T)
#
\end{table}
\end{document}
What I get is this, but the [l] tags hint that there's something else wrong with the tags as well:
On StackExchange TEX I found a question about rotation and linebreaks, this is what I'm trying achieve: https://tex.stackexchange.com/questions/14730/big-table-with-rotated-column-labels-using-booktabs
You could use tableHTML:
library(tableHTML)
Replace the new line character "\n" with the HTML tag <br>:
headers <- c("Item\n(Name)", "Value\n(Number)") %>%
stringr::str_replace_all(pattern = "\\n", replacement = "<br>")
Create a tableHTML object and rotate the headers using add_css_header():
dt_lb %>%
tableHTML(rownames = FALSE,
headers = headers,
escape = FALSE,
widths = c(100, 100),
theme = 'scientific') %>%
add_css_header(css = list(c('transform', 'height', 'text-align'),
c('rotate(-45deg)', '70px', 'center')),
headers = 1:2)
The result looks like this:
Note: you can add more css or default themes. Check out the vignettes for more details:
If you want to create a pdf document, you could use RMarkdown:
---
title: "tableHTML2pdf"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
\
```{r}
library(tableHTML)
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
headers <- c("Item\n(Name)", "Value\n(Number)") %>%
stringr::str_replace_all(pattern = "\\n", replacement = "<br>")
dt_lb %>%
tableHTML(rownames = FALSE,
headers = headers,
escape = FALSE,
widths = c(100, 100),
theme = 'scientific') %>%
add_css_header(css = list(c('transform', 'height', 'text-align'),
c('rotate(-45deg)', '70px', 'center')),
headers = 1:2)
```
\
It will then create an HTML file. This file can then be converted to PDF using wkhtmltopdf.
I think you probably rendered your rmarkdown document into HTML... In the rmarkdown yaml header, does it say html_document right now? If so, you can try to change it to pdf_document.....
I rendered a pdf_document with exactly the same code and I think I got what you were looking for...
---
title: "Table Sample"
output: pdf_document
---
``` {r, include = FALSE}
library(tidyverse)
library(kableExtra)
```
```{r}
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
dt_lb %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F,
col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"), align = "c")) %>%
row_spec(0, angle = 90)
```
Latex package makecell was missing.
Hao pointed out that Page 3 of this manual lists some of the necessary Latex packages: haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

Resources