Search code examples
rdataframegt

conditional formatting the cells of a table using gt in R for html rmarkdown file in R


I have a data frame in R called df and I want to conditional format the table apart from column 1 given some criteria: if the value of the cell is between 2 and 3 to be red.From 3 to 4 orange and from 4 to 5 green. How can I do that using the gt library in R ?

df = structure(list(projects = c("Restaurant, Pizzeria and Pasta House Works for  New York",
                                "London Project - New Restaurant  Project", 
                                "Athens - Beautiful Lands for Aigaleo City Project",
                                "Berlin City - Exhibition  near the airport with restaurants",
                                "Pizzeria Buenos Aires New italian restaurant - pasta, tartufo and vino",
                                "area mean value", "total mean value"), 
                    happiness.and.joyfullness = c(3.5,4, 3, 3.2, 4, 5, 3), 
                    joy.for.children = c(3, 5, 3, 4, 5,4, 4), 
                    area = c(3, 5, 3, 3, 3, 4, 4), 
                    damages.from.environment = c(2,4, 2, 3, 3, 5, 5), 
                    approach  = c(3, 1, 5,3, 5, 5, 4), 
                    expensive = c(3, 5, 3, 4, 5, 5, 5), 
                    safety.comes.first = c(5,5, 5, 5, 5, 5, 4),
                    hungry = c(3, 5, 2, 4, 5,5, 5)), 
               row.names = c(NA, -7L), 
               class = c("tbl_df", "tbl","data.frame"))

my take is that I might need a helper function :

cell_style = function(x) {   case_when( x >= 2 & x < 3  ~ cell_fill(color = "red") ,               x >= 3 & x < 4  ~ cell_fill(color = "orange"),              x >= 4 & x <= 5 ~ cell_fill(color = "green"),              TRUE ~ cell_text(color = "black")  ) }```



Also the width of the first column to increase in order to read nicely the big texts that each cell contain on that column . 

Solution

  • You almost had it.

    cell_style <- function(x) {  
      dplyr::case_when( x >= 2 & x < 3  ~ "red",
                 x >= 3 & x < 4  ~ "orange",
                 x >= 4 & x <= 5 ~ "green",
                 TRUE ~ "black") }
    
    gt(df) |>
      cols_width(projects~px(500), -projects~px(100)) |>
      data_color(method="numeric", columns =-1, fn=cell_style)
    

    enter image description here