[R] SUMMARY: aggregate vs. tapply

Joseph LeBouton lebouton at msu.edu
Sun Feb 12 16:36:50 CET 2006


Hi all;

Thanks for the responses to my query of how to make tapply into a table 
instead of an n-dimensional array.  Summary of responses follows:

Peter Dalgaard:
as.data.frame(with(tmp,as.table(tapply(C,list(A=A,B=B),sum))))

Phil Spector wrote:
z = tapply(y,list(var1,var2,var3,var4),sum)
data.frame(do.call('expand.grid',dimnames(z)),y=do.call('rbind',as.list(z)))

Hans Gardfjell:
tmp <- 
data.frame(A=sample(LETTERS[1:5],10,replace=T),B=sample(letters[1:5],10,replace=T),C=rnorm(10))
tmp1 <- with(tmp,aggregate(C,list(A=A,B=B),sum))
tmp2 <- expand.grid(A=sort(unique(tmp$A)),B=sort(unique(tmp$B)))
merge(tmp2,tmp1,all.x=T)

hadley wickham:
Well, you can almost do this in with the reshape package:
tmp <-
data.frame(A=sample(LETTERS[1:5],10,replace=T),B=sample(letters[1:5],10,replace=T),C=rnorm(10))
a <- recast(tmp, A + B ~ ., sum)
# see also recast(tmp, A  ~ B, sum)
add.all.combinations(a, row="A", cols = "B")


Good thing there are so many code cats around, 'cause we have so darn 
many ways to skin 'em. Thanks again to all who took the time to answer!!

-Joseph
-- 
************************************
Joseph P. LeBouton
Forest Ecology PhD Candidate
Department of Forestry
Michigan State University
East Lansing, Michigan 48824

Office phone: 517-355-7744
email: lebouton at msu.edu




More information about the R-help mailing list