KableExtra math symbols - r

How can I insert 'equal or greater than' symbol in a kable?
On the small rmarkdown doc below I tried two different ways based on some
internet suggestions but neither work. I did try the argument 'escape=FALSE' but
it does not work either. Thanks for any pointers...
title: "Math symbols in column headers"
date: "January 15, 2020"
output: pdf_document
---
```{r}
library(kableExtra)
library(knitr)
a <- structure(list(MLE = c(0.0839, 0.2082, 0.4194, 0.8237, 1.6201
), MME = c(0.0839, 0.2082, 0.4194, 0.8234, 1.6147)), class = "data.frame", row.names = c(NA,
5L))
colnames(a) <- c("abundance of\n White Sharks\n $\\\\geq$ 40 inches","Percentage of \n White shark in
the population\n $\\\\geq{40}$ inches")
```
```{r}
kable(a, "latex", booktabs = T)
```
This is what I get...

You need to end up with \geq in the Markdown file. To get that, you enter "\\geq" in the R string, and specify escape = FALSE in the call to kable(). That is,
---
title: "Math symbols in column headers"
date: "January 15, 2020"
output: pdf_document
---
```{r}
library(kableExtra)
library(knitr)
a <- structure(list(MLE = c(0.0839, 0.2082, 0.4194, 0.8237, 1.6201
), MME = c(0.0839, 0.2082, 0.4194, 0.8234, 1.6147)), class = "data.frame", row.names = c(NA,
5L))
colnames(a) <- c("Abundance of\n White Sharks\n $\\geq 40$ inches","Percentage of \n White shark in
the population\n $\\geq 40$ inches")
```
```{r}
kable(a, "latex", booktabs = T, escape = FALSE)
```
This gives me
To respect the linebreaks, you need to use the linebreak function from kableExtra, i.e. something like this:
colnames(a) <- linebreak(c("Abundance of\n White Sharks\n $\\geq 40$ inches",
"Percentage of \n White shark in the population\n $\\geq 40$ inches"))
kable(a, "latex", booktabs = TRUE, escape = FALSE, align = "c")
which gives this output:

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}}

KableExtra adding linebreaks in columns with long nonwhitespace strings

I have a long string which I want in a table, for instance 100x the letter A (AAA...). I would like kable to split this string into multiple lines if they don't fit in the table instead of making these strings overflow such as shown
here.
I noticed kable is actually able of doing so, provided there are newlines or -'s in your string, see for instance here.
However, I would like kable to do this splitting on either selected characters or on any character, so the output result would be this, but I don't know how to achieve this. I had a look on SO and in the kableextra documentation, but no luck. Any suggestions?
Below is a chunk to play around with.
---
title: 'rasstasrt'
sansfont: Calibri Light
output: pdf_document
---
```{r setup, include=FALSE}
library(kableExtra);
library(dplyr)
knitr::opts_chunk$set(cache = F)
```
```{r}
dt <-tibble(Items =c("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaaaaAAa", "Item 2", "Item 3"),
Tmd5ext_1 =c("Lorem ipsum "),
Text_2 =c("Duis pos "))
kableExtra::kable(dt, "latex", booktabs = F, col.names =c("Item", "Short Title", "Veryong Title")) %>% column_spec(1:3, width = "5cm", )
```
You can leverage the newline character in latex, \\ and the argument escape = FALSE in kableExtra::kable(). Settting escape = FALSE causes the \\ to be read as newline characters instead of literal \\. Note that because \ is an escape character in R, you need two slashes \\ in order for R to interpret a single slash \, so to get 2 literal slashes \\ you need to put 4 \\\\ in the string.
---
title: 'rasstasrt'
sansfont: Calibri Light
output: pdf_document
---
```{r setup, include=FALSE}
library(kableExtra)
library(dplyr)
knitr::opts_chunk$set(cache = F)
```
```{r}
dt <-tibble(Items = c("AAAAAAAAAAAAAAA\\\\AAAAAAAAAA\\\\AAAAAAAAAAA\\\\AAAAAAAAAAAAA\\\\AAAAAAaaaaAAa",
"Item 2",
"Item 3"),
Tmd5ext_1 = c("Lorem ipsum "),
Text_2 = c("Duis pos "))
kableExtra::kable(dt,
"latex",
booktabs = F,
col.names =c("Item", "Short Title", "Veryong Title"),
escape = FALSE) %>%
column_spec(1:3, width = "5cm")
```
Alternatively, if you wanted to insert the newline after a specific number of characters, you could write a function to do that.
---
title: 'rasstasrt'
sansfont: Calibri Light
output: pdf_document
---
```{r setup, include=FALSE}
library(kableExtra)
library(dplyr)
knitr::opts_chunk$set(cache = F)
```
```{r}
add_return <- function(x, len) {
# intialize empty vector
y <- c()
# start at beginning of string
i <- 1
# Break string up into lengths of len
while(i < nchar(x)) {
y <- c(y,substr(x, i, i + len - 1))
i <- i + len
}
# concatenate the substrings together with the newline characters
paste0(y, collapse = "\\\\")
}
dt <-
tibble(
Items = c(
add_return(
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaaaaAAa",
len = 5
),
"Item 2",
"Item 3"
),
Tmd5ext_1 = c("Lorem ipsum "),
Text_2 = c("Duis pos ")
)
kableExtra::kable(
dt,
"latex",
booktabs = F,
col.names = c("Item", "Short Title", "Veryong Title"),
escape = FALSE
) %>% column_spec(1:3, width = "5cm")
```
You could also use regular expressions to insert the return after a specific character string.
---
title: 'rasstasrt'
sansfont: Calibri Light
output: pdf_document
---
```{r setup, include=FALSE}
library(kableExtra)
library(dplyr)
knitr::opts_chunk$set(cache = F)
```
```{r}
regex_add_return <- function(x, after) {
gsub(pattern = paste0("(",after,")"), replacement = paste0("\\1\\\\\\\\"),x)
}
dt <-
tibble(
Items = c(
regex_add_return(
"AAAAAAAAAAAAAAAz123AAAAAAAAAAAAAAAz123AAAAAAAAAAz123AAAAAAAAAAAAAAAaaaaAAa",
after = "z123"
),
"Item 2",
"Item 3"
),
Tmd5ext_1 = c("Lorem ipsum "),
Text_2 = c("Duis pos ")
)
kableExtra::kable(
dt,
"latex",
booktabs = F,
col.names = c("Item", "Short Title", "Veryong Title"),
escape = FALSE
) %>% column_spec(1:3, width = "5cm")
```
Note that there are 8 slashes in gsub() because the slash is also an escape character for regular expressions, so each literal slash has to be escaped with a slash, but then each slash that is being used as an escape character for regex also has to be escaped again for R, requiring another slash.

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

Create table with subscripts and coloured rows using Bookdown

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

how to make a multiple line table with xtable, longtable

I am trying to to use xtable() and the longtable environment to display a multi=page table.
Currently when you run the code it will show "\scalebox " at the top and then it will cutoff columns of the table.
How do you remove the "\scalebox" at the top and show all the column in a readable manner?
Thank you.
here is the code:
---
title: "test"
output: pdf_document
keep_tex: TRUE
setspace: singlespacing
geometry: margin=1.1cm
header-includes:
- \usepackage{color}
- \usepackage{amsmath}
- \usepackage{xcolor}
- \usepackage{colortbl}
- \usepackage{tabulary}
- \usepackage{tabularx}
- \usepackage{longtable}
- \usepackage{ltxtable}
fig.lp: ('';character)
fig.pos: "H"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE , comment = NA, message= FALSE, warning = FALSE)
```
```{r one, include= FALSE}
n=600
table = data.frame(name = rep(" dakjf aslkj dklsfj aslj ldjs",n),
NUMERICFIELDNUMBERa = rep(10000,n),
NUMERICFIELDNUMBERb = rep(10000,n),
NUMERICFIELDNUMBERc = rep(10000,n),
NUMERICFIELDNUMBERd = rep("1250 + 52.33",n),
NUMERICFIELDNUMBERe = rep("25.6 + 36.25",n),
NUMERICFIELDNUMBERf = rep(10000,n),
NUMERICFIELDNUMBERg = rep(10000,n)
)
head(table)
colnames(table) = c("GROUP NAME",
"Numeric Field Number1",
"Numeric Field Number2",
"Numeric Field Number3",
"Numeric Field Number4",
"Numeric Field Number5",
"Numeric Field Number6",
"Numeric Field Number7"
)
rownames(table) = NULL
```
```{r echo= FALSE, comment = FALSE, message= FALSE, warning = FALSE, results='asis'}
library(xtable)
options(xtable.include.rownames=F)
options(xtable.scalebox=.7)
#options(xtable.tabular.environment = "tabulary")
#options(xtable.width = "7in")
options(xtable.comment=F)
options(xtable.floating = F)
t = xtable(table)
#align(t)= "cccccccc"#"cp{2cm}cp{2cm}cp{2cm}cp{2cm}cp{2cm}cp{2cm}cp{2cm}cp{2cm}" #rep("p{2cm}C",8)#"p{1cm}cccccccc"
#align(t) = "cp{3cm}p{3cm}p{3cm}p{3cm}p{3cm}p{3cm}p{3cm}"
print(t, sanitize.text.function = identity)
```

Resources