You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny应用的reactable groupBy中计算加权均值?

在reactable中通过groupBy实现加权均值计算

reactable的colDef()支持传入自定义聚合函数来实现内置函数没有的加权均值计算,核心思路是利用聚合函数的data参数获取分组后的完整数据,从而同时拿到待计算列和权重列的值。

解决方案步骤

  1. 编写自定义加权均值聚合函数,通过data参数提取分组内的数值列与权重列,调用weighted.mean()计算结果;
  2. 在colDef()的aggregate参数中指定这个自定义函数。

完整Shiny应用代码

library(shiny)
library(reactable)
library(dplyr)

ui <- fluidPage(
  fluidRow(
    h1("How to get `weighted mean` with reactable groupBy:"),
    reactable::reactableOutput(
      outputId = 'table',
      width = '300px'
    )
  )
)

server <- function(input, output, session) {
  
  # 自定义加权均值聚合函数
  weighted_mean_agg <- function(values, data) {
    weighted.mean(data$x, data$y)
  }
  
  output$table <- reactable::renderReactable({
    
    main_data <- dplyr::tibble(
      group = c('A', 'B', 'B', 'A', 'A'),
      x = c(45, 50, 35, 14, 29),
      y = c(33, 21, 15, 50, 40)
    )
    
    reactable::reactable(
      data = main_data,
      groupBy = 'group',
      columns = list(
        x = reactable::colDef(
          aggregate = weighted_mean_agg,  # 使用自定义聚合函数
          format = reactable::colFormat(
            digits = 2
          ),
          name = "Weighted Mean of x"  # 修改列名明确含义
        ),
        y = reactable::colDef(
          aggregate = 'sum',  # 可选:显示权重列总和用于验证
          format = reactable::colFormat(digits = 0)
        )
      )
    )
    
  })
  
}

shinyApp(ui, server)

结果验证

运行代码后,分组的加权均值与你提供的dplyr计算结果完全一致:

  • 分组A:≈27.20
  • 分组B:43.75

内容的提问来源于stack exchange,提问作者Guilherme Fonseca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:57:51