r - Aggregate() with more functions - -


can use aggregate() more functions in such way aggregations stored separate columns , not part of matrix? want have data frame columns group.1, cyl.1, cyl.2, not group.1, cyl.

# 1 function > aggdata <-aggregate(mtcars["cyl"], by=list(vs), fun=mean, na.rm=true) > aggdata   group.1      cyl 1       0 7.444444 2       1 4.571429 > str(aggdata) 'data.frame':   2 obs. of  2 variables:  $ group.1: num  0 1  $ cyl    : num  7.44 4.57 >  # 2 functions > aggdata <-aggregate(mtcars["cyl"], by=list(cyl), fun=function(x) c(length(x),mean(x))) > aggdata   group.1 cyl.1 cyl.2 1       4    11     4 2       6     7     6 3       8    14     8 > str(aggdata) 'data.frame':   3 obs. of  2 variables:  $ group.1: num  4 6 8  $ cyl    : num [1:3, 1:2] 11 7 14 4 6 8 > aggdata$cyl      [,1] [,2] [1,]   11    4 [2,]    7    6 [3,]   14    8 

wrap in do.call(data.frame, ...):

aggdata <-aggregate(mtcars["cyl"], by=list(mtcars$cyl),                      fun=function(x) c(length(x),mean(x))) do.call(data.frame, aggdata) #   group.1 cyl.1 cyl.2 # 1       4    11     4 # 2       6     7     6 # 3       8    14     8 str(do.call(data.frame, aggdata)) # 'data.frame': 3 obs. of  3 variables: #  $ group.1: num  4 6 8 #  $ cyl.1  : num  11 7 14 #  $ cyl.2  : num  4 6 8 

after searching little bit, found the source of answer. there few other questions similar this, learned do.call(data.frame, ...) approach.

(came mind search after @james added same answer did , deleted his....)


Comments