根据单元格值使用kableExtra为行着色 [英] Coloring rows with kableExtra based on cell values
问题描述
我结合使用R markdown和LaTeX来创建PDF报告.要生成表,我使用kableExtra包.
I use R markdown in combination with LaTeX to create PDF reports. To generate tables I use the kableExtra package.
我想根据特定列中的值更改行的样式.我一直在尝试cell_spec,但据我所知,它仅更改列中值的样式,而不更改整个行中的值.
I'd like to change the styling of rows based on the values in a particular column. I've been trying cell_spec, but as far as I can see it only changes the styling of the value in the column and not the entire row.
例如,在下表中,我要突出显示所有具有六个以上气缸的汽车.所以结果应该是:
For example, in the table below I'd like to highlight all cars with more than six cylinders. So the result should be:
我用以下代码编写了
df %>%
kable(booktabs = T) %>%
kable_styling() %>%
row_spec(5, bold = T, color = "white", background = "red")
在这里我指定了行号,我不想这样做.应根据气缸数自动确定.使用cell_spec,我可以得到以下信息:
Here I specified a row number, which I don't want to do. It should be decided automatically based on the number of cylinders. Using cell_spec, I'm able to get the following:
我用以下代码编写了
df %>%
rownames_to_column('cars') %>% # used to store row names (mutate deletes them)
mutate(
cyl = cell_spec(cyl, color = ifelse(cyl > 6, "white", "black"),
background = ifelse(cyl > 6, "red", "white"),
bold = ifelse(cyl > 6, T, F))) %>%
column_to_rownames('cars') %>% # used to put row names back in place
kable(escape = F, booktabs = T) %>%
kable_styling()
但这只会更改圆柱列中的值,而不会更改其余行中的值.
But this changes only the value in the cylinder column, and not the rest of the row.
有没有解决我的问题的方法(最好不为每个样式选项指定条件)?
Is there a solution to my problem (preferrably without specifying the condition for every styling option)?
这与此人的问题不同,有人要根据该列中的值设置列的格式,但希望排除某些行/条目.我不想排除任何行,但是我希望格式应用于整个行(仍然以特定列中的值为条件).
This is a different question than this one, where someone wants to format a column based on values in that column, but wishes to exclude certain rows/entries. I don't want to exclude any rows, but I want the formatting to apply to the entire row (still conditioning on values in a particular column).
推荐答案
我认为最简单的方法是根据您的条件传递要着色的行列表.
I think the easiest way is to pass a list of row to be coloured based on your criterias.
library(kableExtra)
df<- mtcars
color.me <- which(df$cyl >6)
df %>%
kable(booktabs = T) %>%
kable_styling() %>%
row_spec(color.me, bold = T, color = "white", background = "red")
或与以下管道位于同一管道中:
or in the same pipe as:
df %>%
kable(booktabs = T) %>%
kable_styling() %>%
row_spec(which(df$cyl >6), bold = T, color = "white", background = "red")
这篇关于根据单元格值使用kableExtra为行着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!