[R] aggregate with cumsum

David Winsemius dwinsemius at comcast.net
Tue Oct 12 20:09:03 CEST 2010


On Oct 12, 2010, at 1:40 PM, Bond, Stephen wrote:

> Hello everybody,
>
> Data is
> myd <-  
> data.frame(id1=rep(c("a","b","c"),each=3),id2=rep(1:3,3),val=rnorm(9))
>
> I want to get a cumulative sum over each of id1. trying aggregate  
> does not work
>
> myd$pcum <- aggregate(myd[,c("val")],list(orig=myd$id1),cumsum)
>
Use ave instead of aggregate:

 > ave(myd$val, list(myd$id1), FUN=cumsum)
[1]  0.362123399 -1.538797831 -2.061733393 -2.038050242 -0.344382401  
-1.365281650
[7]  0.391181119 -0.258668053 -0.007736216

myd$pcum <- ave(myd$val, list(myd$id1), FUN=cumsum)

> Please suggest a solution. In real the dataframe is huge so looping  
> with for and subsetting is not a great idea (still doable, though).
> Thank you
>
>
> Stephen B
-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list