0

我正在使用reactableR 中的包构建表格。行有 2 种渐变配色方案中的 1 种,具体取决于它们所属的组(在我的示例年份中)。这工作正常。但是,现在我想使用另一个变量向表中添加一个嵌套结构(它变得太大)。想想国家内的地区。但是,我无法巧妙地总结国家层面的汇总结果。如果我使用sum我得到总和,而我想保持一个地区和国家内年份的原始分解。因此,我不想聚合一个值,而是聚合到两个值。理想情况下,我还想在组的标题中保留颜色渐变方案(Y1 为蓝色,Y2 为红色)。我怎样才能在自定义中写这个JS()功能?还是有其他方法可以做到这一点?

library(reactable)
library(tidyverse)

my_df <- data.frame(region = rep(1:4, each =2),
                    country = rep(c("country_1", "country_2"), each = 4),
                    year= rep(c("Y1", "Y2"), 2),
                    var1 = c(3, 1, 3, 4, 2, 3, 3, 4),
                    var2 = c(2, 3, 3, 5, 4, 3, 4, 2),
                    var3 = c(1, 2, 4, 1, 5, 1, 4, 5))

make_color_pal <- function(colors, bias = 1) {
  get_color <- colorRamp(colors, bias = bias)
  function(x) rgb(get_color(x), maxColorValue = 255)
}


f_pct_color_1 <- make_color_pal(c("#ffffff",  "#E01F54"), bias = 1)
f_pct_color_2 <- make_color_pal(c("#ffffff", "#001852"), bias = 1)



reactable(
  my_df,
  groupBy = "country",
  defaultColDef =  colDef(
    aggregate = "sum",
    class = "cell",
    style = function(value, index, name) {
      if (my_df[index, "year"] == 'Y1') {
        list(background = f_pct_color_1(
          value / my_df %>%
            filter(year   == "Y1") %>%
            ungroup() %>%
            select(-region, -country  ,-year ) %>%
            max()
        ))
      } else{
        list(background = f_pct_color_2(
          value / my_df %>%
            filter(year   == "Y2") %>%
            ungroup() %>%
            select(-region, -country  ,-year ) %>%
            max()
        ))
      }
    }
  ),
  columns = list(
    region     = colDef(style = list(), aggregate = "count"),
    country    = colDef(style = list(), aggregate = "count"),
    year    = colDef(style = list(), aggregate = "count")
  )
)
4

0 回答 0