[R] count the cumulative for each subject

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Nov 24 21:52:28 CET 2008


Bart Joosen wrote:
> Peter,
> 
> After I made a small modification it worked:
> with(dat, ave(x1, subject, FUN=cumsum))

Right. I forgot that it doesn't follow the pattern of tapply.

(If someone could cook up a more evokative name than "ave", we could 
change this at the same time. grapply() perhaps? or maybe split.apply().)

> But what's the use of with?
> If I use ave(x1, subject, FUN=cumsum), I get the same result?


Only if dat is attached. You were using dat$x1 in your code, so I 
assumed that it wasn't...

> Bart
> 
> ----- Original Message ----- From: "Bart Joosen" <Bartjoosen at hotmail.com>
> To: "Peter Dalgaard" <P.Dalgaard at biostat.ku.dk>
> Cc: <r-help at r-project.org>
> Sent: Monday, November 24, 2008 7:29 PM
> Subject: Re: [R] count the cumulative for each subject
> 
> 
>> Peter,
>>
>> I actually took a look at the ave function, but couldn't manage to get 
>> it right.
>> But when I try your code, I get "Error in as.vector(x, mode) : invalid 
>> argument 'mode'".
>> Any ideas?
>>
>> Bart
>>
>> ----- Original Message ----- From: "Peter Dalgaard" 
>> <P.Dalgaard at biostat.ku.dk>
>> To: "bartjoosen" <bartjoosen at hotmail.com>
>> Cc: <r-help at r-project.org>
>> Sent: Monday, November 24, 2008 3:42 PM
>> Subject: Re: [R] count the cumulative for each subject
>>
>>
>> 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
>>
>>
> 


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