Can I use aggregate()
with more functions in such way that aggregations are stored as separate columns and not as part of a matrix? I want to have data frame with columns Group.1, cyl.1, cyl.2
, not Group.1, cyl
.
# Only one 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
>
# Two 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