[R] cumsum and subsets of a data frame?

John Fox jfox at mcmaster.ca
Wed Jul 24 18:45:46 CEST 2002


Dear Michael,

The following appears to do what you want:

     > cbind(tmp, s=c(lapply(split(tmp, tmp$f),
     +     function(x) cumsum(x$y)), recursive=T))
         f x  y   s
     1   left 1  0   0
     2   left 2  0   0
     3   left 3  9   9
     4   left 4 10  19
     5   left 5 23  42
     6   left 6 45  87
     7   left 7 13 100
     8   left 8  2 102
     9   left 9  6 108
     10 right 1 10  10
     11 right 2 26  36
     12 right 3  9  45
     13 right 4 50  95
     14 right 5 78 173
     15 right 6 20 193
     16 right 7  7 200
     17 right 8 20 220
     18 right 9 19 239

I hope that this helps,
  John

At 09:29 AM 7/24/2002 -0500, 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:
>
> > tmp
>        f x  y   s
>1   left 1  0   0
>2   left 2  0   0
>3   left 3  9   9
>4   left 4 10  19
>5   left 5 23  42
>6   left 6 45  87
>7   left 7 13 100
>8   left 8  2 102
>9   left 9  6 108
>10 right 1 10  10
>11 right 2 26  36
>12 right 3  9  45
>13 right 4 50  95
>14 right 5 78 173
>15 right 6 20 193
>16 right 7  7 200
>17 right 8 20 220
>18 right 9 19 239
>
>I know how to calculate the pieces with, for example,
>
> > cumsum(tmp$y[tmp$f=='right'])
>
>but I don't know how to get this piecewise into the data frame or
>how to automate it.  Any suggestions?

____________________________
John Fox
Department of Sociology
McMaster University
email: jfox at mcmaster.ca
web: http://www.socsci.mcmaster.ca/jfox
____________________________

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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