Create table with subscripts and coloured rows using Bookdown - r

I am attempting to generate a PDF from a Bookdown script which includes a complex table. The table includes some parameter names that have subscripts in them. I would also like to colour some of the rows. An example script is shown below:
---
title: "Example problem"
author: "Frida Gomam"
site: bookdown::bookdown_site
documentclass: book
output:
#bookdown::gitbook: default
bookdown::pdf_book: default
always_allow_html: yes
---
This is a test example for the problem.
```{r}
library(magrittr)
library(knitr)
library(kableExtra)
df <- data.frame(Parameter = c("NO~x~ emissions", "SO~2~ emissions", "CO~2~ emissions"), "Value mg/Nm^3^" = c(800,900,1000),check.names=F)
knitr::kable(df,escape = F, caption = 'Example table!', booktabs = TRUE, format = "latex") %>% #
row_spec(0, bold = T, color = "white", background = "#045a8d") %>%
row_spec(c(2), bold = T, color = "white", background = "#3690c0")
```
blah blah
I can run the script using the kable format as 'format = "html"' and the result looks fine including the coloured rows and subscripts. When I change the format to Latex, the subscripts are not displayed properly in the produced pdf.
I have tried adding the argument escape = F to kable, but the build process fails.
Quitting from lines 14-23 (_main.Rmd)
Error in kable_latex(x = c("$NO_{x}$ emissions", "SO2 emissions", "CO2 emissions", :
unused argument (example = FALSE)
Calls: <Anonymous> ... eval -> %>% -> eval -> eval -> <Anonymous> -> do.call
Can anyone help solve this problem?

For me it works if I use (escaped) LaTeX syntax:
---
title: "Example problem"
author: "Frida Gomam"
site: bookdown::bookdown_site
documentclass: book
output:
bookdown::pdf_book: default
#bookdown::gitbook: default
always_allow_html: yes
---
This is a test example for the problem.
```{r}
library(magrittr)
library(knitr)
library(kableExtra)
df <- data.frame(Parameter = c("NO\\textsubscript{x} emissions", "SO\\textsubscript{2} emissions", "CO\\textsubscript{2} emissions"),
"Value mg/Nm\\textsuperscript{3}" = c(800,900,1000),
check.names = F)
knitr::kable(df,escape = F, caption = 'Example table!', booktabs = TRUE, format = "latex") %>% #
row_spec(0, bold = T, color = "white", background = "#045a8d") %>%
row_spec(c(2), bold = T, color = "white", background = "#3690c0")
```
blah blah

Related

RMarkdown Change numbering for tables in PDF document

I want to change the numbering of the tables in the RMarkdown document so that all tables in the appendix have an "A-" in front of the number, thus: "Table A-2".
Only in the appendix. Otherwise with normal numbering ("Table 1").
However, I am not really getting anywhere.
Here is my reproducible example:\
---
title: "This is my title"
date: "`r Sys.setlocale(locale = 'English') ; format(Sys.time(), '%B %d, %Y')`"
output: pdf_document
---
```{r echo = F, message = F, warning = F}
library(tidyverse)
library(knitr)
``` #The hash mark must be removed!
# Results
```{r echo = F, message = F, warning = F}
tribble(~column1, ~column2,
"value1", 2,
"value2", 5
)%>%
kable(booktabs=T, caption = "This is the caption of the first table")
```
# Appendix
```{r echo = F, message = F, warning = F}
tribble(~column1, ~column2,
"value1", 6,
"value2", 8
)%>%
kable(booktabs=T, caption = "This is the caption of the second table")
```
This is really a LaTeX question, and I found the answer here.
You add these LaTeX lines after your Appendix title:
\setcounter{table}{0}
\renewcommand{\thetable}{A\arabic{table}}

R Aligning table content to decimal points in kable

I've created a table in RMarkdwon (PDF) with the knitr and kableExtra packages.
I can choose in the kable-function between left,center or right- alignments.
But I want that the content of the table cells are aligned to the decimal points.
In this case it is difficult since there are asterisks behind the numbers indicating the significance.
Here is a reproduceable example:
library(tidyverse)
library(knitr)
library(kableExtra)
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
kable(format = "latex", booktabs=T, escape = T)%>%
kable_styling(position = "center", latex_options = "hold_position")
Which produces this table:
Can someone give me an easy solution directly in R?
If this should not be possible, how would an edit in the latex code look like?
Many thanks in advance!
Here is the table provided by bttomio:
One solution could be intersing the variable names in {} recommended by https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf page 28.
The code then looks like this:
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
rename_all( ~ str_c("{ ",.," }"))%>%
kable(format = "latex", booktabs=T, escape = T)%>%
kable_styling(position = "center", latex_options = "hold_position")
And the table corresponds to the desired output:
But the problem is the full-width-option in the kable_styling-function. If I set this option to TRUE the linebreak of large column names disappears.
Here is a first try:
---
output: pdf_document
header-includes:
- '\usepackage{siunitx}'
- '\newcolumntype{d}{S[table-format=3.2]}'
---
```{r}
library(tidyverse)
library(knitr)
library(kableExtra)
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
kable(format = "latex", booktabs=T, escape = T, align = "d")%>%
kable_styling(position = "center", latex_options = "hold_position")
```

column_spec function in kableExtra in R doesn't work

I want co change column width in pdf with kable ( , 'latex') but the fucntion doesn't work. Anybody know why? here is my code:
table = knitr::kable(jeden, "latex" , row.names = F , align = "llrrrrrrrrrr" , escape = F, booktabs = F, caption = '1. Sprzedaz uslug i towarow razem')
kableExtra::column_spec(table, 1, width = "1cm", bold = TRUE, italic = TRUE)
It's not a bug but rather a relatively strange setting for align in knitr::kable(). In xtable you can put align in a string but for kable, you will have to provide a vector. In your case, if you put things like align = c(rep("l", 2), rep("r"), 2), you should be fine.
It seems that align breaks your column_spec, but only for LaTeX/PDF output.
Here are two minimal & reproducible examples.
PDF output
---
title: "Untitled"
output:
pdf_document: default
---
```{r}
library(knitr)
library(kableExtra)
x <- kable(head(mtcars[, 1:4]), "latex", row.names = F, align = "llrr")
column_spec(x, 1:2, width = "4cm", bold = TRUE, italic = TRUE)
```
If you remove align from the PDF RMarkdown document, column_spec works as expected.
HTML output
---
title: "Untitled"
output:
html_document: default
---
```{r}
library(knitr)
library(kableExtra)
x <- kable(head(mtcars[, 1:4]), "html", row.names = F, align = "llrr")
column_spec(x, 1:2, width = "4cm", bold = TRUE, italic = TRUE)
```
This seems like a bug to me, and I would suggest opening an issue on the kableExtra GitHub site. If you do, you should reference this post, and include a minimal & reproducible example (similar to what I did).

Rmarkdown Kable with custom background colors knits successfully, but fails when called from render

I have written an Rmarkdown file that loads some data and generates a kableExtra table with some symbols and custom colors and lines, printing it to pdf.
It works when I open the Rmarkdown file and knit, and produces the exact output that I want. For various reasons I need to call this Rmarkdown file from another .R file.
However, when I do this (using the rmarkdown::render function), I get an error that doesn't occur when knitted directly from within the .Rmd file. Specifically, the errors are caused by setting background within the cell_spec function; removing this call to set the background color allows me to successfully render the .Rmd file from another file. The error is:
! Illegal parameter number in definition of \reserved#a.
<to be read again>
f
l.111 ...; background-color: #ffe6e6;" >1</span>}}
\\
Thanks so much for any advise.
Here is a complete Rmd file that reproduces the issue. The output when knitted directly from Rmd looks like this:
Here is the code.
---
title: ""
always_allow_html: yes
output:
pdf_document:
latex_engine: xelatex
geometry: margin=0.3in
header-includes:
- \usepackage[T1]{fontenc}
- \usepackage{array}
- \usepackage{booktabs}
- \usepackage{xcolor}
- \usepackage{makecell}
- \usepackage{longtable}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{hyperref}
- \setmainfont{Helvetica}
- \pagenumbering{gobble}
- \DeclareTextCommand{\nobreakspace}{TU}{\leavevmode\nobreak\ }
documentclass: article
classoption: a4paper
---
```{r, echo=FALSE, message = FALSE, warning = FALSE}
# Packages
suppressMessages(library(ggplot2))
suppressMessages(library(extrafont))
suppressMessages(library(dplyr))
suppressMessages(library(pander))
suppressMessages(library(kableExtra))
# Data
table_dat <- data.frame(latex_symbol = c("", "$\\blacktriangle$",
"$\\blacklozenge$", "$\\blacklozenge$",
"$\\bullet$", "+"),
color = c("#0c0000", "#ffde71", "#cb6f86",
"#0c0000", "#0c0000", "#0c0000"),
name = c("Thing 1", "Thing 2", "Thing 3",
"Thing 4", "Thing 5", "Thing 6"),
latex_font_size = c(14, 11, 8, 11, 16, 8),
value = c(1,"<0",3,4,5,6),
stringsAsFactors = FALSE)
fsize <- 12
bgcolor <- c(rep("#ffe6e6",2), rep("#ffffff", 4))
table_dat$value <- cell_spec(table_dat$value, background = bgcolor)
ktable <- table_dat %>%
rename(color_ = color) %>%
mutate(latex_symbol = cell_spec(latex_symbol, color = color_,
font_size = latex_font_size,
escape = FALSE,
format = "latex")) %>%
select(latex_symbol, name, value) %>%
kable(escape = FALSE, align = rep("l", 3),
booktabs = TRUE, format = "latex",
col.names = c("Symbol", "Name", "Value"),
linesep = "") %>%
row_spec(1:6, color = "darkgray") %>%
row_spec(0, bold = TRUE) %>%
column_spec(1, "5em") %>%
column_spec(2, "11em") %>%
column_spec(3, "4em") %>%
kable_styling(font_size = fsize) %>%
row_spec(1, bold = TRUE) %>%
row_spec(1:4, hline_after = TRUE)
```
```{r, echo=FALSE}
ktable
```
Note: the reason for so many packages being cited explicitly in the header is that I've had issues similar to this in the past that were solved by citing all of the packages associated with kable in my header before rendering. However, that didn't seem to solve my problem this time.

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