cell_spec for conditional cells

Viewed 422

I have a table currently looking like this:

current table

I want to do a cell_spec that essentially follows: if the cell = X & Amount = 5, then background = "yellow" if cell = X & Amount = 4, then background = "green"

etc for all values.

to look like this: what I would like

I've looked online and can't figure out the function to make this work.

1 Answers

Using cell_spec you could try something like this, assuming dataframe df:

library(kableExtra)
library(tidyverse)

df %>%
  mutate_all(~cell_spec(.x, background = case_when(.x == "X" & Amount == 5 ~ "yellow",
                                                   .x == "X" & Amount == 4 ~ "green",
                                                   .x == "X" & Amount == 3 ~ "blue",
                                                   .x == "X" & Amount == 2 ~ "purple",
                                                   .x == "X" & Amount == 1 ~ "grey",
                                                   TRUE ~ "white"))) %>%
  kable(escape = F) %>%
  kable_styling()
Related