我有一个关于R中的reactable的问题。我有一个分组的df,其中已经进行了一些计算,例如相对数字和总和。根据我的理解,可以使用内置的函数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")

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))发布于 2020-04-24 09:45:09
虽然这可以使用自定义聚合函数来实现,但我认为使用自定义聚合单元格渲染器会更容易: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]
}
}
}
")
)
)

如果有帮助,cellInfo.subRows和cellInfo.column属性都记录在上面的链接中。
https://stackoverflow.com/questions/61384721
复制相似问题