Re: [R] count the cumulative for each subject

From: Daniel Malter <daniel_at_umd.edu>
Date: Mon, 24 Nov 2008 02:43:07 -0500


Hi,

subject=c(1,1,1,2,2,2)
visit=c(1,2,3,1,2,3)
x1=c(0.5,1.2,0.7,0.4,0.6,0.1)

cum=NULL #initialize
for(i in 1:length(subject)){
cum[i]=sum(x1[subject[i]==subject&visit[i]>=visit]) }

I am sure there is a way with tapply or similar functions that is computationally more efficient. But if your dataset is not very large, the above function does the job very well.

Cheers,
Daniel



cuncta stricte discussurus

-----Ursprüngliche Nachricht-----
Von: r-help-bounces_at_r-project.org [mailto:r-help-bounces_at_r-project.org] Im Auftrag von gallon li
Gesendet: Monday, November 24, 2008 2:22 AM An: r-help
Betreff: [R] count the cumulative for each subject

I have a data set like the following:

subject visit x1

1 1 0.5
1 2 1.2
1 3 0.7
2 1 0.4
2 2 0.6
2 3 1.0

.....

where x1 is the interval between the two visits. Now I want to calculate the cumulative intervals since the beinging, for example

 subject visit x1 cum

1 1 0.5 0.5
1 2 1.2 0.5+1.2
1 3 0.7 0.5+1.2+0.7
2 1 0.4 0.4
2 2 0.6 0.4+0.6
2 3 1.0 0.4+0.6+1.0

.....

is there an easy to generate the last veriable cum? The number of visits for each subject may be different.

I also want to choose a subset which correspond to the last observation of each subject. I am also wondering if there is a fast way to do so.

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

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. Received on Mon 24 Nov 2008 - 07:44:55 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 24 Nov 2008 - 09:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive