R-反应物-groupBy-在顶部显示总数

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

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

I have noticed that you could create your own custom JS function。不幸的是我没有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 react-table
1个回答
0
投票

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

自定义单元格渲染器可以访问更多信息,例如列的名称(或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.subRowscellInfo.column属性全部记录在上面的链接中,如果有帮助。

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