我正在尝试使用 r markdown
、 kable
和 kableExtra
输出 latex 表。我需要使用条件逻辑将颜色添加到带有 cell_spec 的表格中。但是对于pdf输出,它显示的 latex 代码如下;
pdf output with latex code
如果我在 escape = false
中添加 kable()
,它会给我以下错误,
我是 rmarkdown
和 latex 的新手,请帮我解决这个问题。谢谢你。
这是我的 rmd 文件代码:
---
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")
}
```
最佳答案
此错误是由于数据框中有下划线“_”造成的。在这种情况下,列名称包含下划线。在 TeX 中,此符号用于在数学环境中设置下标。这就是为什么在普通文本中使用时必须对其进行转义( \_
)的原因。删除,转义或替换下划线,例如
names(data) <- gsub("_", "", names(data)) # remove
names(data) <- gsub("_", "\\_", names(data)) # escape
names(data) <- gsub("_", " ", names(data)) # replace with space
关于r - 错误 : Missing $ inserted when using kable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53606025/