captain
captain

Reputation: 633

How can I color the same value in the same color in the entire gt table in R?

I have a gt table in R and want to color all of the values in the same color. For example, using the mtcars dataset, how could I color all values of 0 in red and all values of 4 in blue?

library("gt")
mtcars %>% 
  gt()

I tried to use tab_style() and data_color() with no success so far. To be clear, I want an easy solution that will work with tables that have dozens of columns, without having to add myriads of additional tab_style() and data_color() or other additional arguments, if that's possible.

Upvotes: 2

Views: 588

Answers (2)

TarJae
TarJae

Reputation: 78917

If we want to change the font colors only then we could use cell_text and make use of @akrun's loop solution, see also here change font color conditionally in multiple columns using gt():

library(dplyr)
library(gt)
tbl1 <- mtcars %>%
  gt()
nm1 <- names(mtcars)
for(i in seq_along(nm1)) {
  
  tbl1 <- tbl1 %>%
    tab_style(
      style = list(
        cell_text(color = "red", weight = "bold")
        
      ),
      locations = cells_body(
        columns = nm1[i],
        
        rows = tbl1$`_data`[[nm1[i]]] == 0 
      )
    ) %>%
    
    tab_style(
      style = list(
        cell_text(color = "blue", weight = "bold")
        
      ),
      locations = cells_body(
        columns = nm1[i],
        
        rows = tbl1$`_data`[[nm1[i]]] == 4 
      )
    ) 
  
}
tbl1

enter image description here

Upvotes: 1

akrun
akrun

Reputation: 886948

We could use a for loop

library(dplyr)
library(gt)
tbl1 <- mtcars %>%
     gt()
 nm1 <- names(mtcars)
 for(i in seq_along(nm1)) {
      
      tbl1 <- tbl1 %>%
        tab_style(
          style = list(
            cell_fill(color = "red")
            
          ),
          locations = cells_body(
            columns = nm1[i],
            
            rows = tbl1$`_data`[[nm1[i]]] == 0 
          )
        ) %>%
        
        tab_style(
          style = list(
            cell_fill(color = "blue")
            
          ),
          locations = cells_body(
            columns = nm1[i],
            
            rows = tbl1$`_data`[[nm1[i]]] == 4 
          )
        ) 
        
    }

-output

enter image description here

Upvotes: 1

Related Questions