为何kable()/column_spec()仅高亮部分指定值而非全部?
问题原因与解决办法
为啥第9行的12.5没高亮?
你的代码里有两个冲突点导致了这个问题:
- 条纹样式优先级更高:你启用了
kable_styling的striped选项,它会给交替行添加默认条纹背景色,这个样式的优先级比column_spec设置的列单元格背景色高。第9行刚好属于条纹行,所以黄色高亮被条纹背景盖住了。 - 虽然你的
ifelse逻辑本身是对的(Δ>15时用白色,否则用黄色),但架不住条纹样式的背景会覆盖它。
修正后的代码
换用row_spec单独给符合条件的行设置Δ列背景,强制覆盖条纹样式:
library(dplyr) library(kableExtra) question_results <- data_frame( '#' = 1:15, 'Pre-Test Avg.' = c(10, 60, 20, 30, 30, 20, 0, 30, 50, 0, 10, 30, 20, 40, 30), 'Post-Test Avg.' = c(87.5, 100, 100, 37.5, 75, 75, 87.5, 87.5, 62.5, 12.5, 87.5, 100, 62.5, 50, 100) ) question_results$'$\Delta$' <- question_results$'Post-Test Avg.' - question_results$'Pre-Test Avg.' # 筛选出Δ值小于15的行索引 highlight_rows <- which(question_results$'$\Delta$' < 15) kable(question_results, align = "cccc", caption = "Question Data", format="latex", position = "h!", escape = FALSE) %>% row_spec(0, bold=TRUE) %>% # 给目标行的Δ列设置黄色背景,用!important强制覆盖条纹样式 row_spec(highlight_rows, background = "yellow", extra_css = "!important;") %>% kable_styling(latex_options = c("striped")) %>% footnote(general = c("$\\Delta$ denotes simple change in value: Post-Test Score minus Pre-Test Score."), escape = FALSE, footnote_as_chunk = TRUE, threeparttable = TRUE)
核心改动
- 用
which()定位出需要高亮的行号 - 用
row_spec替代column_spec,针对目标行设置背景,并通过!important强制覆盖条纹背景 - 删除原有的
column_spec语句,避免样式冲突
内容的提问来源于stack exchange,提问作者RKeithL
相关产品推荐
相关产品推荐

