rgt

Conditionally color cells based on different column in gt


I would like to conditionally color cells based on a different column using gt package. I tried using the rows argument to conditionally color but it doesn't work. Here I tried a reproducible example:

library(gt)
library(dplyr)
head(mtcars) %>%
  gt() %>%
  data_color(
    columns = cyl,
    rows = vs == 0,
    palette = c("red", "green")
  )

Output:

enter image description here

As you can see it doesn't color right and the other values. It should be red if vs is 0 and green if vs is 1. Does anyone know how we can conditionally color these values based on a different column in gt?


Solution

  • Use target_columns=.

    head(mtcars) %>%
      gt() %>%
      data_color(
        columns = vs, target_columns = cyl,
        palette = c("red", "green")
      )
    

    gt table with all of cyl column colored per the values of the vs columns

    Think of the use of rows= as a filtering component, it limits which rows are affected by the coloring, not how the colors are assigned.

    Incidentally, I tried in my head to assuming that palette= might support a named-vector in a way that ggplot2::scale_*_manual(values=) supports, but it's not automatic ... you need to use fn= if you want to control which value/level goes to which color.

    ... %>%
      data_color(
        columns = vs, target_columns = cyl,
        fn = function(x) coalesce(c("0"="green", "1"="red")[as.character(x)], "gray")
      )
    

    I don't know if there's a scales:: equivalent that handles NA values correctly.