Search code examples
rkablekableextra

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


I would like to replicate the following table that in tableau is called Spotlighting

enter image description here

In my case I would like to replicate it with the following base that gives me color to the maximum value per row that are the questions I have an idea to do it with cell_spec() from the kableExtra package

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)

enter image description here

Remember that I want to get a table with a similar format only that now I will only show the largest number in the table


Solution

  • Loop through the numeric columns and add a colour based on the value (change the ifelse statement as needed):

    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)
    

    enter image description here


    Edit:

    To do the same per row, we can transpose, then as above loop through columns and change the colour based on value, then transpose it back again:

    # 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)
    

    enter image description here