函数
aggregate(x, ...)## Default S3 method:
aggregate(x, ...)
## S3 method for class 'data.frame'
aggregate(x, by, FUN, ..., simplify = TRUE, drop = TRUE)
## S3 method for class 'formula'
aggregate(formula, data, FUN, ..., subset, na.action = na.omit)
## S3 method for class 'ts'
aggregate(x, nfrequency = 1, FUN = sum, ndeltat = 1, ts.eps = getOption("ts.eps"), ...)
参数说明:
1、by:分组元素列表,要求每个元素与数据框中元素一致。使用方式如:by=list(name1=groupvar1, name2=groupvar2, ... , groupvarN)(1)对单个因子进行数据计算
> vars<-c("mpg","hp","wt")
> aggregate(mtcars[vars],by=list(am=mtcars$am),mean)
am mpg hp wt1
0 17.14737 160.2632 3.7688952
1 24.39231 126.8462 2.411000
> aggregate(mtcars[vars],by=list(mtcars$am),mean)
Group.1 mpg hp wt1
0 17.14737 160.2632 3.7688952
1 24.39231 126.8462 2.411000
(2)多因子的数据计算如下案例是分别根据cy1、gear对应的分组情况,计算mpg、hp、wt对应的均值。
> attach(mtcars)
> vars<-c("mpg","hp","wt")
> aggregate(mtcars[vars],by=list(cyl,gear),mean,simplify = FALSE)
Group.1 Group.2 mpg hp wt1
4 3 21.5 97 2.4652
6 3 19.75 107.5 3.33753
8 3 15.05 194.1667 4.1040834
4 4 26.925 76 2.3781255
6 4 19.75 116.5 3.093756
4 5 28.2 102 1.82657
6 5 19.7 175 2.778
8 5 15.4 299.5 3.37
2、formula:公式,如y~x或者复合函数cbind(y1,y2)~x1+x2的公式,其中变量y(y1,y2)的值是根据分组因子x(x1,x2)对数据分组操作而得到的
> aggregate(cbind(mpg,hp)~cyl+gear,FUN=mean)
cyl gear mpg hp1
4 3 21.500 97.00002
6 3 19.750 107.50003
8 3 15.050 194.16674
4 4 26.925 76.00005
6 4 19.750 116.50006
4 5 28.200 102.00007
6 5 19.700 175.00008
8 5 15.400 299.5000
> aggregate(mpg~am,FUN = mean)
am mpg1
0 17.147372
1 24.39231
[size=9.000000pt]


雷达卡



京公网安备 11010802022788号







