我编写了一个 Rmarkdown 文件,它加载一些数据并生成一个带有一些符号和自定义颜色和线条的 kableExtra 表,并将其打印为 pdf。
它在我打开 Rmarkdown 文件并编织时起作用,并产生我想要的确切输出。由于各种原因,我需要从另一个 .R 文件中调用此 Rmarkdown 文件。
但是,当我这样做时(使用 rmarkdown::render 函数),我得到一个错误,该错误在直接从 .Rmd 文件中编织时不会发生。具体来说,错误是由函数内部设置引起background
的cell_spec
;删除此调用以设置背景颜色使我能够成功地从另一个文件呈现 .Rmd 文件。错误是:
! Illegal parameter number in definition of \reserved@a.
<to be read again>
f
l.111 ...; background-color: #ffe6e6;" >1</span>}}
\\
非常感谢您的任何建议。这是重现该问题的完整 Rmd 文件。直接从 Rmd 编织时的输出如下所示:
这是代码。
---
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
```
注意:在标头中明确引用了这么多包的原因是,我过去遇到过类似的问题,通过kable
在渲染之前引用与我的标头中关联的所有包来解决。但是,这一次似乎并没有解决我的问题。