1
votes

The gt package is pretty new but wanted to see if there's a way to conditionally format based on the contents of multiple columns.

gt's default appears to only conditionally format by column.

So in this example both columns are colored identically despite column y being significantly larger.

library(gt)

data.frame(
  x = 1:10, 
  y = 101:110) %>% 
  gt() %>% 

data_color(
  columns = c("x", "y"),
  colors = scales::col_numeric(
    palette = c("#d67f90", "white", "#689d7c"),
    domain = NULL
  )
)

enter image description here

Is it possible to use all the data to conditionally format; in this way the gt table would probably look like this (via good ole' Excel). enter image description here

Thanks!

1

1 Answers

4
votes

You need to set the domain parameter of scales::col_numeric():

library(gt)

df <- data.frame(
  x = 1:10, 
  y = 101:110) 
  
gt(df) %>% 
data_color(
  columns = c("x", "y"),
  colors = scales::col_numeric(
    palette = c("#d67f90", "white", "#689d7c"),
    domain = range(c(df$x, df$y))
  )
)

enter image description here