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

如何基于数值变量分组获取汇总统计?对total变量计算指定指标

问题描述

现有如下data.table格式的数据:

library(data.table)
dat <- fread("total women young
              1       0      0
              1       1      1
              1       0      1
              2       1      1
              2       2      1
              2       2      1
              3       1      2
              3       2      3
              3       2      3
              4       4      2
              4       4      3
              4       3      3
              5       5      2
              5       2      3
              5       5      3
              10       4      2
              10       4      3
              20       5      3
             100      10     20")

需要完成以下操作:

  • 为变量total创建6个类别:1、2、3、4、5以及超过5
  • 统计每个total类别的观测数,存入count列
  • 计算sum_tot_count:类别对应值与count的乘积(“超过5”类别用该组所有total值的总和)
  • 计算每组中women和young的平均值(可保留分数或小数格式)

期望输出如下:

total count sum_tot_count women young
              1       3      3          0.33   0.66
              2       3      6          5/6    0.5
              3       3      9          5/9    8/9
              4       3      12         11/12  10/12
              5       3      15         12/15  8/15
              over 5  4      140        23/140 28/140
解决方案

基于data.table的分组聚合特性,可高效实现需求,具体操作如下:

步骤1:创建分组列

通过fcase函数对total变量进行分组,将大于5的观测归为over 5类别:

dat[, total_group := fcase(
  total == 1, "1",
  total == 2, "2",
  total == 3, "3",
  total == 4, "4",
  total == 5, "5",
  total > 5, "over 5"
)]

步骤2:分组计算统计量

按新生成的分组列聚合,计算每组的观测数、total总和(即sum_tot_count)、women和young的总和:

result <- dat[, .(
  count = .N,
  sum_tot_count = sum(total),
  women_sum = sum(women),
  young_sum = sum(young)
), by = total_group]

步骤3:转换平均值格式

根据需求选择分数或小数格式展示women和young的平均值:

  • 保留分数格式:
result[, `:=`(
  women = paste(women_sum, sum_tot_count, sep="/"),
  young = paste(young_sum, sum_tot_count, sep="/")
)][, c("women_sum", "young_sum") := NULL]
  • 保留两位小数格式:
# result[, `:=`(
#   women = round(women_sum / sum_tot_count, 2),
#   young = round(young_sum / sum_tot_count, 2)
# )][, c("women_sum", "young_sum") := NULL]

步骤4:调整列结构

调整列顺序并修改列名,匹配期望输出:

setcolorder(result, c("total_group", "count", "sum_tot_count", "women", "young"))
setnames(result, "total_group", "total")

最终运行结果如下:

total count sum_tot_count    women     young
1:      1     3             3      1/3       2/3
2:      2     3             6      5/6       3/6
3:      3     3             9      5/9       8/9
4:      4     3            12     11/12     10/12
5:      5     3            15     12/15      8/15
6: over 5     4           140    23/140     28/140

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:26:05