Search code examples
rkableextra

R Using kableExtra to colorize cells and maintain striped formatting with nested if/ifelse?


An expansion to this question: R wanting to limit the amount of digits from csv file

I am using kableExtra and cell_spec to colorize cells with nested ifelse statements.

Instead of colorizing values less than .10 white, I want to leave them alone in order to allow kableExtra to apply the striped formatting.

I have a feeling this isn't possible though because of how the background colors are applied?

DF:

DF <- data.frame(V1 = sample(letters,10,T), V2 = abs(rnorm(10)), V3 = abs(rnorm(10)))

Code:

library(magrittr)
library(kableExtra)
paint <- function(x) {
  ifelse(x < 0.1, "white", ifelse(x < 0.2, "yellow", "red"))
}

DF[, -1] = lapply(DF[, -1], formatC, format = 'f', flag='0', digits = 2)
DF[,-1] = lapply(DF[,-1], function(x) cell_spec(x, background = paint(x), format = "latex"))

DF %<>%
  mutate_if(is.numeric, function(x) {
   cell_spec(x, background = paint(x), format = "latex") 
  })

kable(DF, caption = "colorized table with striping", digits = 2, format = "latex", booktabs = T, escape = F, longtable = T)%>%
  kable_styling(latex_options = c("striped", "hold_position", "repeat_header", font_size = 6))%>%
  landscape()%>%
  row_spec(0, angle = 45)

Problem area?

paint <- function(x) {
      ifelse(x < 0.1, "white", ifelse(x < 0.2, "yellow", "red"))
    }

can this be changed to only change the color if between yellow(>=.10<.2) and red(>=.2)? Or do all conditions have to be defined?

Desired output: a striped table that only highlights values as defined, allowing the stripes to exist on values less than .10


Solution

  • You don't need to apply any formatting to the cells you wish to leave alone. So just test for that condition before calling cell_spec (i.e., only call cell_spec for those cells you want to format):

    paint <- function(x) ifelse(x < 0.2, "yellow", "red")
    
    DF[,-1] = lapply(DF[,-1], formatC, format = 'f', digits = 2)
    DF[,-1] = lapply(DF[,-1], function(x) 
      ifelse(x < 0.1, x, cell_spec(x, background = paint(x), format = "latex")))
    
    kable(DF, caption = "Highlighted numbers near zero", 
      digits = 2, format = "latex", booktabs = T, escape = F, longtable = T) %>%
      kable_styling(latex_options = c("striped", "hold_position", 
        "repeat_header", font_size = 6)) %>%
      landscape() %>%
      row_spec(0, angle = 45)