Search code examples
rdt

R datatable styleColorBar based on different column


I would like to have a styleColorBar in my datatable where the size of the bar is based on a different column.

iris %>% 
  select(Species, Petal.Length) %>% 
  group_by(Species) %>% 
  mutate(avg_petal = mean(Petal.Length)) %>% 
  datatable() %>% 
    formatStyle(
        'Petal.Length',
        background = styleColorBar(iris$Petal.Length, 'steelblue'),
        backgroundSize = '100% 90%',
        backgroundRepeat = 'no-repeat',
        backgroundPosition = 'center'
    )

How can I add a color bar to the Species column based on the avg_petal column?

Is this possible?


Solution

  • You could use valueColumns argument so that datatable knows that a numeric column is used for formating, and then pass the formatting data$avg_petal to styleColorBar.

    library(DT)
    
    data <- iris %>% 
      select(Species, Petal.Length) %>% 
      group_by(Species) %>% 
      mutate(avg_petal = mean(Petal.Length))
    
    data %>%  datatable() %>% 
      formatStyle(
        'Species', valueColumns = "avg_petal",
        background = styleColorBar(data$avg_petal, 'steelblue'),
        backgroundSize = '100% 90%',
        backgroundRepeat = 'no-repeat',
        backgroundPosition = 'center'
      )
    

    enter image description here