按组计算累积和(cumsum) [英] Calculate cumulative sum (cumsum) by group

查看:26
本文介绍了按组计算累积和(cumsum)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有数据框:

df <- data.frame(id = rep(1:3, each = 5)
                 , hour = rep(1:5, 3)
                 , value = sample(1:15))

我想添加一个与 id 匹配的累积总和列:

I want to add a cumulative sum column that matches the id:

df
   id hour value csum
1   1    1     7    7
2   1    2     9   16
3   1    3    15   31
4   1    4    11   42
5   1    5    14   56
6   2    1    10   10
7   2    2     2   12
8   2    3     5   17
9   2    4     6   23
10  2    5     4   27
11  3    1     1    1
12  3    2    13   14
13  3    3     8   22
14  3    4     3   25
15  3    5    12   37

我怎样才能有效地做到这一点?谢谢!

How can I do this efficiently? Thanks!

推荐答案

df$csum <- ave(df$value, df$id, FUN=cumsum)

ave 是首选"函数,如果您想要一个与现有向量长度相等的按组向量,并且可以单独从这些子向量计算它.如果您需要基于多个并行"值的按组处理,则基本策略是 do.call(rbind, by(dfrm, grp, FUN)).

ave is the "go-to" function if you want a by-group vector of equal length to an existing vector and it can be computed from those sub vectors alone. If you need by-group processing based on multiple "parallel" values, the base strategy is do.call(rbind, by(dfrm, grp, FUN)).

这篇关于按组计算累积和(cumsum)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆