Ellie
Ellie

Reputation: 21

can't apply cell_spec() across multiple columns in kableExtra

I'm trying to apply cell_spec to multiple columns in a data.frame but keep getting error messages Here is some dummy code: I want to highlight all values less than 1

df <- data.frame(vars =c("a","b","c","d","e","f","g","h"), d1 = c(0.5,1,5,7,9,3,4,1), d2 = c(0.6,3,5,4,7,9,4,2), d3 = c(4,2,5,7,9,2,2,3))


I am able to apply to a single cell like so:

df[1,2] = cell_spec(df[1,2], background = "green")

enter image description here

But this is time consuming to highlight all cell individually

I have tried using lapply

df[,2:4] <- lapply(df[,2:4], cell_spec(df[,2:4], background = ifelse(df[,2:4] < 2, "green", "white")))
df %>% kable(digits = 3, escape = FALSE, booktabs = TRUE) %>% kable_styling(bootstrap_options = "striped", latex_options="scale_down") 

and get this error:

Error in match.fun(FUN) : c("'cell_spec(para_p[, 2:4], background = ifelse(para_p[, 2:4] < ' is not a function, character or symbol", "'
2, "green", "white"))' is not a function, character or symbol")

And I've tried writing a function

df <- mutate_if(is.numeric, function(i){cell_spec(i, background = ifelse(i < .05, "green", "white"))}) %>%
  kable(digits = 3, escape = FALSE, booktabs = TRUE) %>% kable_styling(bootstrap_options = "striped", latex_options="scale_down")  

But get this error:

Error in UseMethod("tbl_vars") : no applicable method for 'tbl_vars' applied to an object of class "function"

Any help would be very much appreciated! Thanks in advance

Upvotes: 0

Views: 275

Answers (1)

Ben
Ben

Reputation: 30474

One approach using tidyverse. Using mutate with across can apply a function to multiple selected columns.

library(kableExtra)
library(tidyverse)

df %>%
  mutate(across(d1:d3, ~cell_spec(.x, background = if_else(.x < 2, "green", "white")))) %>%
  kable(digits = 3, escape = FALSE, booktabs = TRUE) %>% 
  kable_styling(bootstrap_options = "striped", latex_options="scale_down") 

Table

table with background color green or white for cells

Upvotes: 0

Related Questions