rgt

gt colour Rows with data_color


I have a gt table in R and want to color each rows based on the percentage difference to the target of that row

  library(gt) 
  # Example dataset 
  mydata <- data.frame( Col1 = c(10, 12, 15, 8, 9),
                  Col2 = c(20, 22, 25, 18, 19),
                  Col3 = c(30, 32, 35, 28, 29),
                  Col4 = c(40, 42, 45, 38, 39),
                  Target = c(100, 105, 110, 95, 100) 
                  )

  mydata$Diff <- (mydata$Target - mydata[, 1:4]) / mydata$Target * 100 

  mytable <- mydata %>% 
    gt() %>%
    data_color(scale = list( 
         Col1 = c("red","green"),
         Col2 = c("red","green"),
         Col3 = c("red","green"),
         Col4 = c("red","green"),
         Diff = c("red","green")
      ),
      colors = "Diff",
      apply_to = cells_body(columns = 1:5),
      reverse_colors = TRUE ) 

   mytable

I have tried the data_color () without any success. Here with data_color I keep getting "Error in data_color(., scale = list(Col1 = c("red","green"), : unused arguments " . I am expecting a gradient of colour for each row


Solution

  • I wonder if this code would support your needs. I used library(tidyverse) to create the Diff columns because I most familiar with creating new columns through this approach.

    library(gt) 
    # Example dataset 
    mydata <- data.frame( Col1 = c(10, 12, 15, 8, 9),
                      Col2 = c(20, 22, 25, 18, 19),
                      Col3 = c(30, 32, 35, 28, 29),
                      Col4 = c(40, 42, 45, 38, 39),
                      Target = c(100, 105, 110, 95, 100) 
    ) %>% 
    mutate(
      DiffCol1 = (Target -Col1)/Target,
      DiffCol2 = (Target -Col2)/Target, 
      DiffCol3 = (Target -Col3)/Target, 
      DiffCol4 = (Target -Col3)/Target
    )
    
    library(gt)
    
    gt(mydata) %>% 
    data_color(   columns = DiffCol1,
                target_columns = Col1,
                method = "numeric",
                palette = c('red', 'green')
                ) %>% 
    cols_hide(DiffCol1:DiffCol4)
    

    Example with Diff columns hidden

    Example with diff columns displayed

    library(gt)
      gt(mydata) %>% 
      data_color(   columns = DiffCol1,
                    target_columns = Col1,
                    method = "numeric",
                    palette = c('red', 'green')
                    ) %>% 
        data_color(   columns = DiffCol2,
                      target_columns = Col2,
                      method = "numeric",
                      palette = c('red', 'green')
        ) %>% 
        data_color(   columns = DiffCol3,
                      target_columns = Col3,
                      method = "numeric",
                      palette = c('red', 'green')
        ) %>% 
        data_color(   columns = DiffCol4,
                      target_columns = Col4,
                      method = "numeric",
                      palette = c('red', 'green')
        ) 
    

    All Columns