kableExtra中colortbl的\cellcolor与\makecell共用单元格填充不全方案问询
可行规避方案
以下两种方案均无需手动修改中间tex文件,可直接用于批量生成场景:
方案1:指定列宽自动换行(推荐)
完全避开有冲突的\makecell命令,通过column_spec设置列宽实现自动换行,不需要提前对字符串做换行处理:
library(kableExtra) library(tidyverse) # 数据准备 df <- tribble( ~col1, ~col2, "really long text that needs to be broken into multiple lines so it can fit", 4, "really long text that needs to be broken", 4, "really long text that needs a fix", 4, ) # 生成表格 df %>% kbl(escape = FALSE, format = "latex") %>% # 直接指定第一列宽度实现自动换行,宽度数值可按需调整 column_spec(col = 1, width = "25em", align = "l") %>% row_spec(row = 1:3, background = "#e5e5e5")
该方案兼容性最好,适合绝大多数不需要精准控制换行位置的场景。
方案2:注入LaTeX补丁兼容linebreak用法
如果需要手动控制换行位置、必须使用linebreak函数,可以在Rmd文件的YAML头部添加LaTeX补丁,底层修复colortbl和makecell的冲突:
--- output: pdf_document: header-includes: - \makeatletter - \renewcommand\makecell[2][c]{% \ifx\@cellcolor\@undefined \begin{tabular}[#1]{@{}c@{}}#2\end{tabular} \else \@cellcolor\begin{tabular}[#1]{@{}c@{}}#2\end{tabular} \global\let\@cellcolor\@undefined \fi } - \makeatother ---
添加后原有调用linebreak的表格代码不需要做任何修改,即可实现完整的单元格背景填充。
内容的提问来源于stack exchange,提问作者Yang Wu
相关产品推荐
相关产品推荐

