[R] cumsum and subsets of a data frame?

Thomas Lumley tlumley at u.washington.edu
Wed Jul 24 17:36:36 CEST 2002


On 24 Jul 2002, Michael A. Miller wrote:

> I have a question about using cumsum on subsets of a data frame.
> Suppose I have a frame that looks something like this
>
> > tmp
>        f x  y
> 1   left 1  0
> 2   left 2  0
> 3   left 3  9
> 4   left 4 10
> 5   left 5 23
> 6   left 6 45
> 7   left 7 13
> 8   left 8  2
> 9   left 9  6
> 10 right 1 10
> 11 right 2 26
> 12 right 3  9
> 13 right 4 50
> 14 right 5 78
> 15 right 6 20
> 16 right 7  7
> 17 right 8 20
> 18 right 9 19
>
> I'm plotting things like this will lattice
>
> > library(lattice)
> > xyplot(y ~ x | f, data=tmp)
>
> If I plot the cumsum with xyplot( cumsum(y) ~ x | f, data=tmp),
> it is summed across the values of the factor f.  Can anyone
> suggest a way to calculate the cumulative sum of y in this data
> frame such that it is reset for each value of f?  The resulting
> frame would look like this:
>

Use split and unsplit
Eg
> df<-data.frame(y=runif(100),f=rep(1:5,rep(20,5)))
> df$z<-unsplit(lapply(split(df$y,df$f),cumsum),df$f)


	-thomas


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list