我想复制下表中称为Spotlighting的表格
在我的情况下,我想用以下基础复制它,让我的颜色达到每行的最大值,这是我cell_spec()
从kableExtra
包中想到的问题
library(knitr)
library(kableExtra)
Name<-c("question1", "question", "question3", "question4",
"question5", "question6", "question7", "question8",
"question9", "question10")
A<-c(0, 3 ,0 ,1, 0, 0, 0, 0, 2, 0)
B<-c(5, 0, 1, 0, 3, 0, 3, 1, 0, 1)
C<-c(3, 0, 2 ,2 ,0 ,1, 0 ,1 ,0 ,2)
D<-c(4, 1, 3 ,2 ,0 ,5, 0 ,1 ,3 ,2)
tab<-data.frame("Name"=Name,"A"=A,"B"=B,"C"=C,"D"=D)
tab%>%
kbl() %>%
kable_paper("striped",full_width = F)
请记住,我只想获得一个格式相似的表格,现在我将只显示表格中的最大数字
循环遍历数字列并根据值添加颜色(根据需要更改ifelse语句):
tab %>%
mutate_if(is.numeric,
function(i){
cell_spec(i, color = ifelse(i > 1, "green", "red"))}) %>%
kbl(escape = FALSE) %>%
kable_paper("striped", full_width = FALSE)
编辑:
每行做同样的事情,我们可以转置,然后如上所述循环列并根据值更改颜色,然后再次转置:
# transpose, get colour, transpose
tmp <- data.frame(t(
data.frame(t(tab[ -1 ])) %>%
mutate_all(function(i) cell_spec(i, color = ifelse(i == max(i), "green", "red")))
), row.names = NULL)
# keep 1st name coloumn, add other formatted columns, and kable
cbind(tab[ 1 ], tmp) %>%
kbl(escape = FALSE) %>%
kable_paper("striped", full_width = FALSE)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句