0

I am using the gt() package in R and am having a rough time trying to style my cells based on their content.

Here's a minimal example.

Let's start with a tibble, my_data:

  my_data <- tibble(person = c('pablo','spots','harry'), 
                    outcome_1 = c('good','bad','good'),
                    outcome_2 = c('good','good','bad'))

Let's now try to render a gt table and color the cells that contain the text 'bad' so that they're red.

  my_data |> 
    gt() |>
    
    tab_style(
      
      style = list(
        cell_fill(color = 'red'),
        cell_text(weight = 'bold')),
      
      locations = cells_body(
        columns = starts_with('outcome_'),
        rows = contains('bad')
      )
    )

But it doesn't work! The cells containing the word 'bad' should have bold font weight and should have a red background. Instead I get...

unstyled cells

The example in the docs for locations seems fairly straightforward. I am following what it says in for cells_body usage and as far as I can tell correctly applying the selection helpers starts_with and contains.

So what's the problem? I think I got a fundamental misunderstanding here of how this is supposed to work!

Angelo
  • 2,936
  • 5
  • 29
  • 44

1 Answers1

2

sort of hackish but doing its job:

my_data |> 
  gt() |>
  tab_style(
    style = list(
      cell_fill(color = 'red'),
      cell_text(weight = 'bold')),
    locations = names(my_data)[grep('outcome', names(my_data))] |>
      lapply(FUN = \(col_name){
        cells_body(columns = col_name,
                   rows = grepl('bad', my_data[[col_name]])
                   )
      })
    )
  )

It works because you can supply a list of cells_body selections, which is what lapply produces (here as an inline call).

I_O
  • 4,983
  • 2
  • 2
  • 15
  • Thank you! I've upvoted will accept if there's no more compact version. I just can't remember all that, it looks really complicated. The examples which just apply colors to a range of values are so simple-looking. I am hoping this could be simple too. – Angelo Jun 09 '23 at 13:02
  • You're welcome. The following solution (although from Sept. 2020, but then again, by @akrun) suggests there's no straightforward indexing by cell content alone: https://stackoverflow.com/a/63945239/20513099 – I_O Jun 09 '23 at 13:09