Quarto文档中基于LaTeX与kable实现表格行条件加粗问题求助
Quarto表格LaTeX渲染时条件整行加粗的解决办法
之前代码的问题
- 第一个版本里的
extra_css = "font-weight: bold;"只适用于HTML输出,LaTeX不认CSS样式,所以渲染后加粗效果消失。 - 第二个版本的两个明显错误:
any(str_detect(...))是对整个列做全局判断,不是逐行检查,导致所有行的标记结果都一样,没法精准定位要加粗的行。- 还是用了
extra_css参数,LaTeX环境下这个参数不起作用。
正确的实现代码
df.result %>% select(Drug, Variant, Interpretation, Drug.Resistance.Prediction) %>% mutate(Variant = str_replace_all(Variant, pattern = ",", ",\n")) %>% kable(format = "latex", escape = FALSE, col.names = c("Drug", "Result", "Interpretation", "Drug Resistance Prediction")) %>% column_spec(c(2,4), width = "5.5 cm") %>% kable_styling(latex_options = "HOLD_position") %>% row_spec(row = which(str_detect(df.result$Interpretation, "-R")), font_weight = "bold")
关键调整点
- 明确指定
format = "latex":让kable生成LaTeX格式的表格代码,适配Quarto的LaTeX渲染。 - 把
extra_css换成font_weight = "bold":这是kableExtra专门给LaTeX表格设置加粗的参数,对LaTeX渲染有效。 - 用
str_detect(df.result$Interpretation, "-R")逐行检测:准确筛选出Interpretation列包含"-R"的行号,确保只给目标行加粗。
更稳妥的管道内标记版本
如果担心依赖外部原数据框可能出问题,可以在管道里直接标记目标行,再应用样式:
df.result %>% select(Drug, Variant, Interpretation, Drug.Resistance.Prediction) %>% mutate( Variant = str_replace_all(Variant, pattern = ",", ",\n"), is_bold = str_detect(Interpretation, "-R") ) %>% kable(format = "latex", escape = FALSE, col.names = c("Drug", "Result", "Interpretation", "Drug Resistance Prediction")) %>% column_spec(c(2,4), width = "5.5 cm") %>% kable_styling(latex_options = "HOLD_position") %>% row_spec(row = which(.$is_bold), font_weight = "bold") %>% select(-is_bold) # 删掉标记列,不让它显示在表格里
内容的提问来源于stack exchange,提问作者natural_d
相关产品推荐
相关产品推荐

