Calculate cumulative sum within each ID (group)

烂漫一生 提交于 2019-11-26 14:41:18
df$csum <- ave(df$value, df$id, FUN=cumsum)

To add to the alternatives, data.table's syntax is nice:

library(data.table)
DT <- data.table(df, key = "id")
DT[, csum := cumsum(value), by = key(DT)]

Or, more compactly:

library(data.table)
setDT(df)[, csum := cumsum(value), id][]

The above will:

  • Convert the data.frame to a data.table by reference
  • Calculate the cumulative sum of value grouped by id and assign it by reference
  • Print (the last [] there) the result of the entire operation

"df" will now be a data.table with a "csum" column.

Using library plyr.

library(plyr)
ddply(df,.(id),transform,csum=cumsum(value))
Tjebo

Using dplyr::

require(dplyr)
df %>% group_by(id) %>% mutate(csum = cumsum(value))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!