Search code examples
rgt

gt conditional color based on dynamic column names & filtered rows


I'm trying to color a text, based on a specific values for selected rows & columns. Since column names are dynamically changed I cannot use them as a reference, hence I'm struggling with a final code. I would like to mark all the values as red < 0 but only when Name = 'Row2'. For the rest I'd like to do the opposite, mark as red > 0 when Name != 'Row2'. I'm including only first part of the code which doesn't work. I'd like to ask for help about the logic in general. Thank you!

enter image description here

data %>% gt() %>% 
  tab_style(
        locations = cells_body(
          columns = 2:4,
          rows = 'Name' == "Row2" & 4 < 0
        ),
        style = list(cell_text(color = 'red')))

Solution

  • One option would be to use purrr::reduce (or base Reduce) to loop over the column names and apply the style to each column one by one like so:

    data <- data.frame(
      Name = paste0("Row", 1:3),
      Col_june = c(1, -1, 0),
      Col_june2 = c(2, 3, -2),
      Col_june3 = c(3, -2, 2)
    )
    
    library(gt)
    library(rlang)
    
    data %>% 
      gt() %>% 
      purrr::reduce(names(data)[2:4], function(x, y) {
        tab_style(x,
          locations = cells_body(
            columns = all_of(y),
            rows = Name == "Row2" & !!sym(y) < 0
          ),
          style = list(cell_text(color = 'red')))  
      }, .init = .)
    

    enter image description here