Search code examples
rconditional-formattinggt

Conditional formatting of table cells


I am completely new to r, and so I apologise in advance for any rookie mistakes.

I am working with a df containing a large number of TRUE/FALSE, and I want to colour them accordingly - TRUE = green and FALSE = no colour.

The table as of now

Any advice on how to accomplish this in simple, straight forward manner would be much appreciated!

This is as far as I got:

Kube_Liten %>% 
  select(-shape.size) %>% 
  gt() %>% 
  tab_header(
    title = 'Liten Kube',
    subtitle = 'True/False Comparison'
  ) %>% 
  opt_align_table_header(align = 'left')

Solution

  • The answer given by @Kat is excellent, but I think it will be somewhat difficult for a "Novice" to fully understand it. I think it will be easier for you to understand the use of a simple for loop.

    Using the same table from @Kat's answer, you could do something like this:

    df <- gt(df1)
    
    for (i in seq_len(ncol(df1))) {
      df <- df %>%
        tab_style(
          style = cell_text(color = "green"),
          locations = cells_body(columns = names(df1[i]), rows = df1[i] == TRUE)
        )
    }
    df 
    

    In case you would like to learn more about the !! operator, particularly in the context !!sym("x"), check out this answer: What does the !! operator mean in R, particularly in the context !!sym("x"). Here is another answer that explains this syntax.
    When you feel ready for more advanced topics, a good place to start is this.