Search code examples
rr-markdownknitrkableextra

kableExtra linebreak cannot produce line breaks


I want to perform a line break in a table as stated at this document of Best Practice for newline in LaTeX table. However, something doesn't work and I do not get to know why. I think it's due to the string lengths or something.

This is my minimal reproducible example. If I try to knit this in a markdown document with PDF (and Html, replacing "latex" by "html" in kable()) output, It crashes.

library(dplyr, warn.conflicts = F)
library(kableExtra)

dd <- structure(
  list(data_source = seq(1:10), 
       data = c("53 records \nx 9 values \n= 477 data points", 
                "618019 records \nx 11 values \n= 6798209 data points", "4639 records \nx 22 values \n= 102058 data points", 
                "24691 records \nx 50 values \n= 1234550 data points", "30 records \nx 8 values \n= 240 data points", 
                "42 records \nx 
                3 values \n= 126 data points", "963 records \nx 2 values \n= 1926 data points", 
                "56295 records \nx 4 values \n= 225180 data points", "12 records \nx 5 values \n= 60 data points", 
                "8362826 data points (704744 records)")), 
  row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame")
)

dd %>% 
  mutate_all(linebreak) %>% 
  kable("latex", booktabs = T, escape = F)

The error is the following. I've tried the debugging tips, but I didn't get any more useful information about the error.

! Missing $ inserted.
<inserted text> 
                $
l.163 data_
           source & data\\ 

Try to find the following text in Untitled.Rmd:
  data_ 

You may need to add $ $ around a certain inline R expression `r ` in Untitled.Rmd (see the above hint). See https://github.com/rstudio/rmarkdown/issues/385 for more info.
Error: LaTeX failed to compile Untitled.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See Untitled.log for more info.
Execution halted

Any ideas?


Solution

  • The underscore is a special math character in LaTeX. Since you asked kable not to escape it (I'm assuming the variable F has the value FALSE), you need to escape it yourself, or rename the first column with no underscore.