[R] basic question
Marc Schwartz
MSchwartz at MedAnalytics.com
Thu Apr 21 18:24:27 CEST 2005
<snip>
Oops...I forgot one more, using 'test.s' as per the prior e-mail:
test.s <- split(test, test$year)
> sapply(test.s, function(x) colSums(x[, -1]))
2000 2001
x 95 105
y 31 114
z 94 97
or transpose using t():
> t(sapply(test.s, function(x) colSums(x[, -1])))
x y z
2000 95 31 94
2001 105 114 97
which is similar of course to the use of aggregate():
> aggregate(test[, -1], list(Year = test$year), sum)
Year x y z
1 2000 95 31 94
2 2001 105 114 97
The key difference is that aggregate() returns a data frame, whereas
sapply() returns a matrix in this case.
So, see ?sapply as well.
HTH,
Marc Schwartz
More information about the R-help
mailing list