For the following dataset:
d = data.frame(date = as.Date(as.Date(\'2015-01-01\'):as.Date(\'2015-04-10\'), origin = \"1970-01-01\"),
group = re
As this question was tagged with data.table
, you are probably looking for (a modification of @Franks comment).
setDT(d)[order(date), new := cumsum(value), by = group]
This will simultaneously rearrange the data by date
(not sure if needed, if not, you can get rid of order(date)
) and update your data set in place utilizing the :=
operator
Is this it?
sp <- split(d, d$group)
res <- lapply(seq_along(sp), function(i) cumsum(sp[[i]]$value))
res <- lapply(seq_along(res), function(i){
sp[[i]]$c.sum <- res[[i]]
sp[[i]]
})
res <- do.call(rbind, res)
res
This should work
library(dplyr)
d %>%
group_by(group) %>%
arrange(date) %>%
mutate(Total = cumsum(value))
If you just want cumulative sums per group, then you can do
transform(d, new=ave(value,group,FUN=cumsum))
with base R.