R datatable styleColorBar基于不同的列

R datatable styleColorBar based on different column

我想在我的数据表中有一个 styleColorBar,其中条的大小基于不同的列。

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'
    )

如何在 avg_petal 列的基础上向 Species 列添加颜色条?

这可能吗?

您可以使用 valueColumns 参数,以便 datatable 知道数字列用于格式化,然后将格式化 data$avg_petal 传递给 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'
  )