I am attempting to output a latex table using r markdown
, kable
, and kableExtra
. I needed to use conditional logic to add colors to my table with cell_spec. But with the pdf output, it shows latex code as follows;
If I add escape = false
in kable()
, it gives me the following error,
! Missing $ inserted. $ l.142 sepal_ length & sepal_width & petal_length & petal_width & Species\ Here is how much of TeX's memory you used: 14185 strings out of 492970 208670 string characters out of 3125261 323511 words of memory out of 3000000 17834 multiletter control sequences out of 15000+200000 23725 words of font info for 40 fonts, out of 3000000 for 9000 1141 hyphenation exceptions out of 8191 41i,9n,38p,1027b,272s stack positions out of 5000i,500n,10000p,200000b,50000s
I'm new to rmarkdown
and latex, please help me to solve the issue. Thank you.
This is my rmd file code:
---
title: "Iris Data Table"
output: pdf_document
header-includes: \usepackage [table]{xcolor}
geometry: margin = 1cm
params:
n: NA
datafile: "//ad.monash.edu/home/User076/vbed0001/Documents/IRIS.csv" #always set the absolute full path
---
```{r, echo=FALSE, message=FALSE}
d <- read.csv(params$datafile, header = TRUE, sep = ",")
# this uses to remove the warning messages from the pdf file
library(memisc, warn.conflicts = FALSE, quietly=TRUE)
# the package order is important, always kableExtra at the top
#options(kableExtra.latex.load_packages = FALSE)
library(kableExtra)
library(magrittr)
library(formattable)
library(dplyr)
library(knitr)
library(devtools)
options(knitr.table.format = "latex")
if(params$n == "set"){
dtset <- d %>% filter(Species == "setosa")
dtset <- d %>% filter(Species == "setosa")
dtset %>%
mutate(
sepal_length = cell_spec(sepal_length,format = "latex",background = (ifelse(sepal_length>4.5,"#D3D3D3","#ff0000")))
)%>%
kable(format = "latex",caption = "Setosa Table")%>%
kable_styling(position = "center",bootstrap_options = "bordered")
}
```
This error is a result of having underscores "_" in your dataframe. In this case, the column names contain underscores. In TeX this symbol is used to set subscripts in math environments. This is why it has to be escaped (\_
) when used in normal text. Remove, escape or replace the underscores with e.g.
names(data) <- gsub("_", "", names(data)) # remove
names(data) <- gsub("_", "\\_", names(data)) # escape
names(data) <- gsub("_", " ", names(data)) # replace with space