Applying conditional in {gt} summary rows

How can I apply conditional formatting in the summary rows in a gt table if the number is negative?

starwars |> 
  filter(species %in% c("Human", "Droid")) |> 
  count(homeworld, species) |> 
  pivot_wider(
    names_from = species, 
    values_from = n) |> 
  filter(!(is.na(Droid))) |> 
  mutate(diff = Droid - Human) |> 
  gt() |> 
  tab_style(
    style = cell_text(color = "red"),
    locations = list(
      cells_body(columns = diff,
                 rows = diff < 0))) |> 
  grand_summary_rows(
    columns = c(2:4),
    fns = list(`Grand Total` = ~ sum(., na.rm = TRUE)),
    decimals = 0)

I also tried

starwars |> 
  filter(species %in% c("Human", "Droid")) |> 
  count(homeworld, species) |> 
  pivot_wider(
    names_from = species, 
    values_from = n) |> 
  filter(!(is.na(Droid))) |> 
  mutate(diff = Droid - Human) |> 
  gt() |> 
  grand_summary_rows(
    columns = c(2:4),
    fns = list(`Grand Total` = ~ sum(., na.rm = TRUE)),
    decimals = 0) |> 
  data_color(
    columns = diff,
    rows = diff < 0,
    method = "numeric",
    palette = c("red")
  )

but that does not impact the summary rows

(This is, of course, a stupid example since the summary values will always be less than 0 and, in this scenario, could be formatted using cells_grand_summary(). In the real-world, I'm not guaranteed that this value will always be negative.)

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.