Highlighting Values in gt()

gt() is remarkably flexible, but I'm having trouble coming up with a way to use color to draw attention to values evaluated row-wise, as opposed to column-wise, which seems straightforward.

My analysis creates a data set with rows of characteristics and columns for tests done over a variable number of years. It's important the data is presented in this format.

What I would like to do is highlight the maximum value in each row, bearing in mind that the number of columns (i.e., the years) can vary from one analysis to the next. In the example below there are 3 years of data, but in another analysis there may be many more.

data.frame(
  Heading = c("Characteristic 1", "Characteristic 2", "Characteristic 3"),
  `2012` = c(3, 7, 3),
  `2013` = c(4, 2, 2),
  `2014` = c(3, 1, 5),
  Sum = c(10, 10, 10)
) %>% gt()

Ideally, my output would look something like this:

Screen Shot 2020-09-15 at 9.44.44 AM

Any guidance is most appreciated. Thank you

-- Robert

my solution :slight_smile:

library(tidyverse)
library(gt)
library(rlang)
df <- data.frame(
  Heading = c("Characteristic 1", "Characteristic 2", "Characteristic 3"),
  `2012` = c(3, 7, 3),
  `2013` = c(4, 2, 2),
  `2014` = c(3, 1, 5),
  Sum = c(10, 10, 10)
)

names_to_do <- c("X2012", "X2013", "X2014")

(max_row_positions <- map_int(
  names_to_do,
  ~ pull(df, .) %>% which.max()
) %>% setNames(names_to_do))

(maxstyles <- map2_chr(
  seq_along(max_row_positions), max_row_positions,
  ~ paste0("%>% tab_style( style = cell_fill(color = 'lightblue'),
           locations = cells_body(columns = ", 1 + .x, ",rows = ", .y, "))")
))

(code_to_run <- paste0("gt(df)", paste0(maxstyles, collapse = " ")))

eval(parse_expr(code_to_run))

image

1 Like

This topic was automatically closed 21 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.