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

R语言按分组对变量求和:aggregate与group_by使用失败求助

方法1:base R aggregate 实现

正确调用写法如下:

aggregate(votes ~ district + party, data = df, FUN = sum)

你之前调用失败大概率是分组变量或者公式参数填写错误。

方法2:dplyr 包group_by + summarise 实现

group_by仅用来标记分组维度,需要搭配汇总函数summarise才能得到聚合结果,正确写法:

library(dplyr)

df %>% 
  group_by(district, party) %>% 
  summarise(total_votes = sum(votes), .groups = "drop")

末尾的.groups = "drop参数用于取消分组状态,避免后续操作数据时出现非预期结果。

如果需要同时按市政、选区、党派三个维度汇总,将municip也加入分组变量列表即可。两种方法返回的结果一致,如下:

districtpartytotal_votes
oneblue50
onegreen50
onered10
twoblue10
twogreen20

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:15:03