https://blog.csdn.net/hongweigg/article/details/49420111
https://blog.csdn.net/sinat_26917383/article/details/51086663
https://blog.csdn.net/u011219650/article/details/41380265
aggregate函数应该是数据处理中常用到的函数,简单说有点类似sql语言中的group by,可以按照要求把数据打组聚合,然后对聚合以后的数据进行加和、求平均等各种操作。
x=data.frame(name=c("张三","李四","王五","赵六"),sex=c("M","M","F","F"),age=c(20,40,22,30),height=c(166,170,150,155))
构造一个很简单的数据,一组人的性别、年龄和身高,可以用aggregate函数来求不同性别的平均年龄和身高
aggregate(x[,3:4],by=list(sex=x$sex),FUN=mean)
几个注意点:
- 字符或者factor类型的列不要一起加入计算,会报错
- by参数要构造成list,如果有多个字段,by就对应队列,和group by多个字段是同样的道理
x=data.frame(name=c("张三","李四","王五","赵六"),
sex=c("M","M","F","F"),age=c(20,40,22,30),height=c(166,170,150,155))
aggregate(x[,3:4],by=list(sex=x$sex),FUN=mean)
# sex age height
# 1 F 26 152.5
# 2 M 30 168.0
sex=c("M","M","F","F"),age=c(20,40,22,30),height=c(166,170,150,155))
aggregate(x[,3:4],by=list(sex=x$sex),FUN=mean)
# sex age height
# 1 F 26 152.5
# 2 M 30 168.0