[R] aggregate with cumsum
Phil Spector
spector at stat.berkeley.edu
Tue Oct 12 19:48:59 CEST 2010
Stephen -
In version R-2.11.1, I get
> aggregate(myd[,c("val")],list(orig=myd$id1),cumsum)
orig x.1 x.2 x.3
1 a -0.62754524 -1.16194135 -0.05975811
2 b 0.21954618 -0.21355521 -0.62970082
3 c -0.30296239 1.44111610 0.30121880
Since myd has several observations for each value of orig,
you obviously can't just assign the output of aggregate
as a column of myd.
Were you thinking of
merge(myd,aggregate(myd[,c("val")],list(orig=myd$id1),cumsum)) ?
(Note that before version 2.11.1, aggregate *would* fail.))
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Tue, 12 Oct 2010, 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)
>
> 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
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list