一:介绍:
aggregate函数是数据处理中常用到的函数,具有强大的功能。可以按照要求把数据打组聚合,然后对聚合以后的数据进行加和、求平均等各种操作。具体说明可使用命令:help("aggregate")获取官方文档。
aggregate(x, by, FUN, ..., simplify = TRUE, drop = TRUE)
x:an R object.
一个R对象。
by:a list of grouping elements, each as long as the variables in the data frame x. The elements are coerced to factors before use.
一列分组元素,每个与数据框x中的变量等长。元素在使用之前被强制为因子。
FUN:a function to compute the summary statistics which can be applied to all data subsets.
(你需要用于)计算统计汇总信息的函数,会应用于所有数据子集
......
二:应用:
以mtcars数据集演示,按照气缸数分组并求其他各组数据的平均值:
#mtcars:R内置数据集,它是美国Motor Trend收集的1973到1974年期间总共32辆汽车
# 的11个指标: 油耗及10个与设计及性能方面的指标。
# 以下是此应用的三种写法,可供参考:
aggregate(mtcars, by=list(cyl=mtcars$cyl), FUN=mean)
aggregate(mtcars, by=list(cyl),mean)
aggregate(.~cyl,mtcars, mean)
这三种写法得到的结果是一样的,都是按照cyl(气缸数)对车进行分类(比如2缸4缸),每一类分别求其他参数(表里总共11个指标)平均数(比如2缸的车还有不同的里程数等)。下面是结果: