如何使用reactable中的聚合函数来显示与另一列的最小值或最大值关联的值?

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

我正在使用

reactable
包来生成分组表。 当您定义分组变量时,显示会折叠,如下所示:

enter image description here

上表是使用以下内容制作的:

library(reactable)

df<-data.frame(Type=c("Online","Online","Online","RL","RL","RL"),
               DaysBeforeBirthdayParty=c(9,8,7,9,8,7),
               Friends_2018=c(1,2,3,4,5,4),
               Friends_2019=c(10,15,13,19,20,21))

reactable(df,
          groupBy = "Type")

此处提供了在不扩展组的情况下显示聚合的几个选项:https://glin.github.io/reactable/articles/examples.html

我原本打算使用内置的最大值函数,但我的数据是与时间相关的,并且最新的记录并不总是“好友”列中具有最大值的记录。

自定义聚合似乎是所需的工具,链接文章的作者提供了示例:

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(', ')
    }
  ")
)

Javascript 对我来说完全陌生,但是在纯粹使用与 Javascript 相关的查询来搜索答案并根据单独列的最小值或最大值返回值时,语法似乎与此处的示例不同。

我希望更改上面的函数,以便它返回与另一列(DaysBeforeBirthday)中的最小值相关联的一列(例如 Friends_2018)中的值。

期望的结果看起来像(折叠时): enter image description here 并且,展开后:

enter image description here

折叠时显示的 Friends_2018 和 Friends_2019 的值应与 DaysBeforeBirthdayParty 的最小值相关联。

我最成功的尝试是:

library(reactable)

df<-data.frame(Type=c("Online","Online","Online","RL","RL","RL"),
               DaysBeforeBirthdayParty=c(9,8,7,9,8,7),
               Friends_2018=c(1,2,3,4,5,4),
               Friends_2019=c(10,15,13,19,20,21))

###sorting the data so that my row reference in the javascript
###chooses the value I want


df2<-df[order(df$DaysBeforeBirthdayParty),]

reactable(df2,
          groupBy = "Type",
          
          columns = list(
            Friends_2018 = 
          
          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[0]
                           }"))))

这需要我对数据进行预排序并只返回第一行值。

我如何构建它而不依赖于我的预排序?

javascript r reactable
1个回答
0
投票

您应该使用反应脚本中的

defaultExpanded
调用对此进行排序。然后只是 TRUE 或 FALSE。见下图:

reactable(Visual_Test,
          searchable = TRUE,
          defaultSorted = "Overall",
          defaultSortOrder = "desc",
          groupBy = "Division",
          defaultExpanded = TRUE)

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