[R] count the cumulative for each subject

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Mon Nov 24 15:42:44 CET 2008


bartjoosen wrote:
> How about:
> 
> tapply(dat$x1,dat$subject,function(x) cumsum(x))
> which gives you a list for each subject.
> 
> this can be converted to a vector:
> do.call("c",tapply(dat$x1,dat$subject,function(x) cumsum(x)))
> 
> So if your data frame is ordered for your subjects:
> 
> cbind(your.data.frame,do.call("c",tapply(dat$x1,dat$subject,function(x)
> cumsum(x))))
> 
>

Sounds like a job for the eternally overlookked ave() function:

with(dat, ave(x1, subject, cumsum))


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907



More information about the R-help mailing list