Table Spotlighting - 根据多列上的值更改文本颜色

Table Spotlighting - change text colour based on value on multiple columns

我想复制以下 table 在 tableau 中称为 Spotlighting

在我的例子中,我想用下面的基数复制它,它给我颜色到每行的最大值,这是我想用 [=13] 中的 cell_spec() 来做的问题=] 包裹

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)

请记住,我只想获得格式相似的 table,现在我将只显示 table

中的最大数字

遍历数字列并根据值添加颜色(根据需要更改 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 column, add other formatted columns, and kable
cbind(tab[ 1 ], tmp) %>%
  kbl(escape = FALSE) %>%
  kable_paper("striped", full_width = FALSE)