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

如何按性别、分组年龄和分组体重计算pwr变量的聚合均值?

按性别分组计算二维子组的pwr均值实现方案

需求说明

在数据框中按性别分组,以分组年龄(age_cut)为列、分组体重(weight_cut)为行的二维分类子组,计算连续变量pwr的均值。示例如下:

  • sex=male & age 20-24 & weight 60-61时mean_pwr=1310
  • sex=male & age 20-24 & weight 62-63时mean_pwr=1330
  • sex=female & age 40-44 & weight 68-69时mean_pwr=654

示例数据集

age <- seq(20, 65, 1)
weight <- seq(60, 110, 1)
sex <- c("male", "female")
d <- expand.grid(age=age, weight=weight, sex=sex)

d$pwr <- runif(nrow(d), min=100, max=1000)

d$age_cut <- cut(d$age, 9)
d$weight_cut <- cut(d$weight, 25)

实现方法

方法1:使用tidyverse工具链(dplyr + tidyr)

管道式操作简洁直观,适合数据整理场景:

library(tidyverse)

# 分组计算均值并转换为宽表
result_tidy <- d %>%
  group_by(sex, weight_cut, age_cut) %>%
  summarise(mean_pwr = mean(pwr), .groups = "drop") %>%
  pivot_wider(names_from = age_cut, values_from = mean_pwr)

# 查看男性分组结果
result_tidy %>% filter(sex == "male")
  • group_by:按性别、体重分组、年龄分组三个维度划分唯一子组
  • summarise:计算每个子组的pwr均值
  • pivot_wider:将长格式结果转为宽格式,把age_cut的取值设为列,weight_cut设为行,完全匹配需求的二维表结构

方法2:使用Base R的reshape2包

如果习惯base R生态,可通过aggregate和dcast组合实现:

library(reshape2)

# 先计算各子组的pwr均值
mean_data <- aggregate(pwr ~ sex + weight_cut + age_cut, data = d, FUN = mean)

# 分性别转换为宽表
result_male <- dcast(mean_data[mean_data$sex == "male", ], weight_cut ~ age_cut, value.var = "pwr")
result_female <- dcast(mean_data[mean_data$sex == "female", ], weight_cut ~ age_cut, value.var = "pwr")

# 查看女性分组结果
result_female
  • aggregate:按分组变量聚合计算pwr均值,得到长格式的统计结果
  • dcast:将长表转为宽表,指定weight_cut为行、age_cut为列,值为对应的pwr均值,分性别筛选后得到各自的二维统计表格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:39:55