Finding the sum of repeated continuous variables for each subject

Suppose you have a data set with repeated measures --- i.e., you have multiple values of a continuous variable (e.g., var1 and var2 below) for each subject in your data set (each subject could have a different number of records).

d = data.frame(d=c(1,1,1,2,2,4,4,4), var1 = round(rnorm(8),1 ), 
   var2 = c(round(rnorm(8),1)))

You would like to find the sum of the repeated var1 and var2 values for each subject and you would like to keep these results in your original repeated measures data frame.

Here's the 'solution:'

varList = c("var1", "var2")
for (n in varList){
  t = tapply(d[[n]], d$id, sum, na.rm=TRUE)
  d[[paste("sum",n,sep="")]] = t[as.character(d$id)]

This problem and solution were posted by Svetlana Eden.
Topic revision: r2 - 21 Nov 2006, TheresaScott

This site is powered by FoswikiCopyright © 2013-2022 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Vanderbilt Biostatistics Wiki? Send feedback