在R语言中按姓名汇总对应行的年度消费总额
按姓名汇总月度消费计算年度总额的dplyr实现
首先,先把你提供的数据集整理成更清晰的结构(修正了列名和格式):
| Month | Name | Money Spent |
|---|---|---|
| 2 | John Smith | 10 |
| 3 | John Smith | 25 |
| 4 | John Smith | 20 |
| 2 | Joe Nais | 10 |
| 3 | Joe Nais | 25 |
| 4 | Joe Nais | 20 |
你已经在使用dplyr的管道操作了,这很棒!针对你的需求,这里有两种实用的实现方式,取决于你想要的输出形式:
方式1:保留所有月度记录,同时添加年度总额到每行
如果你想保留原始的每一条月度交易数据,同时在每行中显示该用户的年度总消费,可以这样写:
OTData <- OTData %>% # 按姓名分组,让后续的sum针对每个用户单独计算 group_by(`Name`) %>% # 添加新列`Full Year`,值为该用户所有`Money Spent`的总和 mutate(`Full Year` = sum(`Money Spent`)) %>% # 取消分组,避免后续操作意外继承分组规则 ungroup()
运行后,你的数据集会变成这样:
| Month | Name | Money Spent | Full Year |
|---|---|---|---|
| 2 | John Smith | 10 | 55 |
| 3 | John Smith | 25 | 55 |
| 4 | John Smith | 20 | 55 |
| 2 | Joe Nais | 10 | 55 |
| 3 | Joe Nais | 25 | 55 |
| 4 | Joe Nais | 20 | 55 |
方式2:直接生成每个用户的年度总额汇总
如果你只需要每个用户一行的年度总消费结果,用summarize替代mutate即可:
annual_total <- OTData %>% group_by(`Name`) %>% # 汇总每个用户的消费总额,生成新的汇总表 summarize(`Full Year` = sum(`Money Spent`)) %>% ungroup()
这个代码会输出简洁的汇总结果:
| Name | Full Year |
|---|---|
| John Smith | 55 |
| Joe Nais | 55 |
注意事项
因为你的列名(比如Money Spent、Full Year)包含空格,所以必须用反引号`把列名包裹起来,否则R会把空格识别为分隔符,导致语法错误。
内容的提问来源于stack exchange,提问作者Gulshan Chahal
相关产品推荐
相关产品推荐

