# The problem:
# In data.frame d for each "id" find a sum of "var1", "var2"
# and keep the results in the same data.frame .
d = data.frame(ss=c(1111,1111,1111,2222,2222,4444,4444,4444),
id=c(1,1,1,2,2,4,4,4), var1 = round(rnorm(8),1 ), var2 = c(round(rnorm(8),1)))
d
varList = c("var1", "var2")
  # alternative way of defining a list of variables:
  # varList = setdiff(names(d), c("ss", "id"))
for (n in varList){
  t = tapply(d[[n]], d$id, sum, na.rm=TRUE)
  d[[paste("sum",n,sep="")]] = t[as.character(d$id)]
}
Edit | Attach | Print version | History: r2 < r1 | Backlinks | View wiki text | Edit WikiText | More topic actions...
Topic revision: r1 - 08 Nov 2006, TheresaScott
 

This site is powered by FoswikiCopyright © 2013-2017 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