具有更多功能的Aggregate() -

Tom*_*eif 5 aggregate r

我可以使用aggregate()更多函数,以便聚合存储为单独的列而不是矩阵的一部分吗?我希望数据框有列Group.1, cyl.1, cyl.2,而不是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
Run Code Online (Sandbox Code Playgroud)

A5C*_*2T1 9

包裹它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
Run Code Online (Sandbox Code Playgroud)

经过一番搜索,我找到了答案的来源.还有一些类似的问题,但这是我学习这种do.call(data.frame, ...)方法的地方.

(想想在@James添加了与我相同的答案之后要搜索的内容并删除了他的....)


edd*_*ddi 6

这是一个不同的想法 - 切换到data.table:

library(data.table)
dt = data.table(mtcars)

dt[, list(.N, mean(cyl)), by = cyl]
#   cyl  N V2
#1:   6  7  6
#2:   4 11  4
#3:   8 14  8
# note, data.table is smart enough not to copy cyl needlessly
# when you're grouping by it, so if you attempt to get length(cyl), you'll get 1
# since cyl is just a number in each 'by' group

str(dt[, list(.N, mean(cyl)), by = cyl])
#Classes ‘data.table’ and 'data.frame':  3 obs. of  3 variables:
# $ cyl: num  6 4 8
# $ N  : int  7 11 14
# $ V2 : num  6 4 8
# - attr(*, ".internal.selfref")=<externalptr> 
Run Code Online (Sandbox Code Playgroud)