如何在顶部显示groupBy总计?

问题描述 投票:0回答:1

我有一个关于

reactable
中的
R
的问题。我有一个分组 df,其中进行了一些计算,例如相对数字和总和。根据我的理解,可以使用内置函数 max、mean 等来聚合分组的
reactable
。 相反,我想显示名为
show_top
而不是例如
colDef(aggregate = "max")
的行。

我注意到你可以创建自己的自定义 JS 函数。不幸的是我没有JS经验。

colDef(
  aggregate = JS("
    function(values, rows) {
      // input:
      //  - values: an array of all values in the group
      //  - rows: an array of row info objects for all rows in the group
      //
      // output:
      //  - an aggregated value, e.g. a comma-separated list
      return values.join(', ')
    }
  ")
)

请参阅下面我想要实现的目标。

reactable(xy, groupBy = "col1")

enter image description here

structure(list(col1 = c("A", "B", "Tot", "A", "A", "A", "B", 
"B", "B", "Tot", "Tot", "Tot"), col2 = c("show_top", "show_top", 
"show_top", "Type1", "Type2", "Type3", "Type1", "Type2", "Type3", 
"Type1", "Type2", "Type3"), inc = c(" 9.4 (38.7%)", "14.9 (61.3%)", 
"24.2 (100%)", " 3.7 (39.5%)", " 3.3 (35%)", " 2.4 (25.5%)", 
" 2.3 (15.2%)", " 4.6 (31%)", " 8.0 (53.8%)", " 6.0 (100%)", 
" 7.9 (100%)", "10.4 (100%)"), out = c(" 6.0 (39.6%)", " 9.1 (60.4%)", 
"15.1 (100%)", " 2.3 (38.7%)", " 2.1 (35.4%)", " 1.6 (25.9%)", 
" 0.7 (7.3%)", " 2.0 (21.5%)", " 6.5 (71.2%)", " 3.0 (100%)", 
" 4.1 (100%)", " 8.1 (100%)"), rel = c(0.638870535709061, 0.61502998385249, 
0.624251237892968, 0.626302127121007, 0.645747052829909, 0.648875413897266, 
0.296450202443903, 0.42683196642126, 0.813283715858821, 0.501288831579585, 
0.517981542096351, 0.775466939167642), rp = c(49.8379387690741, 
59.4422025881411, 55.229126405081, 46.132952162477, 51.5764509819408, 
53.8145905581141, 14.8399070194007, 32.048326903348, 137.425346172314, 
31.3269996331764, 39.887561604669, 105.790396392544)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -12L))
r reactable
1个回答
1
投票

虽然这可以通过自定义聚合函数来实现,但我认为使用自定义聚合单元渲染器会更容易:https://glin.github.io/reactable/articles/custom-rendering.html# javascript 渲染函数

自定义单元格渲染器可以访问更多信息,例如列的名称(或 ID)。自定义聚合函数更适合对单列中的值列表进行简单操作。

您可以使用 JavaScript 函数自定义所有列的聚合单元格。对于每个聚合单元格,找到

col2
值为
"show_top"
的子行。然后,返回当前列对应的该行中的值。

这是一个例子:

library(reactable)

reactable(
  xy,
  groupBy = "col1",
  defaultColDef = colDef(
    aggregated = JS("
      function(cellInfo) {
        for (var i = 0; i < cellInfo.subRows.length; i++) {
          var row = cellInfo.subRows[i]
          if (row.col2 === 'show_top') {
            return row[cellInfo.column.id]
          }
        }
      }
    ")
  )
)

enter image description here

如果有帮助的话,

cellInfo.subRows
cellInfo.column
属性都记录在上面的链接中。

© www.soinside.com 2019 - 2024. All rights reserved.