如何在LaTeX输出中为kableExtra表格添加样式?
解决kable_styling添加striped选项后LaTeX报错的问题
问题原因
当使用kable_styling(latex_options = "striped")时,这个函数默认会给表格自动包裹一层table浮动环境,但你已经手动在代码里构建了table+subtable的嵌套浮动结构,LaTeX不允许浮动环境嵌套,因此触发报错:! LaTeX Error: Not in outer par mode.(中文翻译:LaTeX错误:不在外部段落模式。)
解决方案
给kable_styling添加position = ""参数,禁用它自动生成的浮动环境,让仅带条纹样式的表格内容直接嵌入你手动定义的subtable中。
修改后的核心代码:
t1 <- kbl(k1, booktabs = TRUE, format = 'latex') %>% kable_styling(latex_options = "striped", position = "") # 不再崩溃
完整可运行代码
--- title: "Table with kable styling options" output: pdf_document params: runs: - Late - Early date: "`r Sys.Date()`" header-includes: - \\usepackage{subcaption} --- ```{r setup, echo=FALSE, include=FALSE} library(kableExtra) library(knitr) library(rmarkdown) k1 <- structure(list(year = c("2011", "2011", "2011", "2011", "2012", "2012", "2012", "2012"), race2 = c("Fall", "LateFall", "Spring", "Winter", "Fall", "LateFall", "Spring", "Winter"), total = c(67174, 1395, 2720, 18126, 70213, 2448, 3590, 29537)), class = "data.frame", row.names = c(NA, -8L))
caption_text1 <- paste("This table represents t1", paste(params$runs, collapse = ", ")) t1 <- kbl(k1, booktabs = TRUE, format = 'latex') %>% kable_styling(latex_options = "striped", position = "") # 正常运行 cat(sprintf("\\\\begin{table}[htb] \\\\caption{Global caption} \\\\centering \\\\begin{subtable}[t]{0.48\\\\textwidth} \\\\centering \\\\caption{%s} %s \\\\end{subtable}%% \\\\end{table} ", caption_text1, t1))
内容的提问来源于stack exchange,提问作者Salvador
相关产品推荐
相关产品推荐

