Conditional formatting of multiple columns in gt table
Solution 1:
I know this is probably too late to help you, but I was able to figure it out by defining a function that creates a list of cells_body calls with the correct parameters. This list is then passed to the locations parameter and applies the specified formatting to all the selected cells. Hopefully someone else finds this useful!
library(gt)
samples = as_tibble(cbind("Chem"=c("Cd","Pb","Zn"),
"Limit"=c("0.005","0.05","0.007"),
"SampA" = c("0.001","0.15","0.003"),
"SampB" = c("0.002","0.04","0.005"),
"SampC" = c("0.009","0.23","0.03")))
builder <- function(x, Limit){cells_body(columns = !!sym(x), rows = !!sym(x) > Limit)}
gt(samples,rowname_col="Chem") %>%
tab_style(style = list(cell_fill(color = "grey80"), cell_text(weight = "bold")),
locations = lapply(c("SampA", "SampB", "SampC"), test_fun, Limit = sym(Limit))) %>%
tab_spanner(label = "Samples", columns = c(SampA, SampB, SampC))
This will work with any vector of strings that match your column names, including what can be created through the colnames()
function
names <- colnames(samples)[3:ncol(samples)]
gt(samples,rowname_col="Chem") %>%
tab_style(style = list(cell_fill(color = "grey80"), cell_text(weight = "bold")),
locations = lapply(names, builder, Limit = sym(Limit))) %>%
tab_spanner(label = "Samples", columns = c(SampA, SampB, SampC))