Coloring rows with kableExtra based on cell values

SPK.z picture SPK.z · Nov 16, 2018 · Viewed 11.3k times · Source

I use R markdown in combination with LaTeX to create PDF reports. To generate tables I use the kableExtra package.

I'd like to change the styling of rows based on the values in a particular column. I've been trying cell_spec, but as far as I can see it only changes the styling of the value in the column and not the entire row.

For example, in the table below I'd like to highlight all cars with more than six cylinders. So the result should be:

enter image description here

Which I made with the following code:

df %>% 
  kable(booktabs = T) %>%
  kable_styling() %>%
  row_spec(5, bold = T, color = "white", background = "red")

Here I specified a row number, which I don't want to do. It should be decided automatically based on the number of cylinders. Using cell_spec, I'm able to get the following:

enter image description here

Which I made with the following code:

df %>%
  rownames_to_column('cars') %>% # used to store row names (mutate deletes them)
  mutate(
  cyl = cell_spec(cyl, color = ifelse(cyl > 6, "white", "black"),
                  background = ifelse(cyl > 6, "red", "white"),
                  bold = ifelse(cyl > 6, T, F))) %>%
  column_to_rownames('cars') %>% # used to put row names back in place
  kable(escape = F, booktabs = T) %>%
  kable_styling()

But this changes only the value in the cylinder column, and not the rest of the row.

Is there a solution to my problem (preferrably without specifying the condition for every styling option)?

EDIT: This is a different question than this one, where someone wants to format a column based on values in that column, but wishes to exclude certain rows/entries. I don't want to exclude any rows, but I want the formatting to apply to the entire row (still conditioning on values in a particular column).

Answer

Jrakru56 picture Jrakru56 · Nov 16, 2018

I think the easiest way is to pass a list of row to be coloured based on your criterias.

library(kableExtra)

df<- mtcars
color.me <- which(df$cyl >6)

df %>% 
  kable(booktabs = T) %>%
  kable_styling() %>%
  row_spec(color.me, bold = T, color = "white", background = "red")

or in the same pipe as:

df %>% 
  kable(booktabs = T) %>%
  kable_styling() %>%
  row_spec(which(df$cyl >6), bold = T, color = "white", background = "red")