[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
我们经常可能需要把一个数据按照某一属性分组,然后计算一些统计值。在R语言里面,aggregate函数就可以办到。
## S3 method for class 'data.frame' aggregate(x, by, FUN, ..., simplify =
TRUE, drop = TRUE)
我们常用到的参数是:x, by, FUN。
x, 你想要计算的属性或者列。
by, 是一个list,可以指定一个或者多个列作为分组的基础。
FUN, 指定一个函数,用来计算,可以作用在所有分组的数据上面。
假如这个是我们的数据。
type<-c("a","b","c","a","c","d","b","a","c","b") value<-c(53,15,8,99,76,22,46,
56,34,54) df<-data.frame(type,value) df type value 1 a 53 2 b 15 3 c 8 4 a 99 5
c76 6 d 22 7 b 46 8 a 56 9 c 34 10 b 54
分组求和
aggregate(df$value, by=list(type=df$type),sum) type x 1 a 208 2 b 115 3 c 118
4 d 22
分组求平均值
分组求平均很简单,只要将上面的sum改成mean就可以了。
aggregate(df$value, by=list(type=df$type),mean) type x 1 a 69.33333 2 b
38.33333 3 c 39.33333 4 d 22.00000
分组计数,分组计数就是在分组的情况下统计rows的数目。
aggregate(df$value, by=list(type=df$type),length) type x 1 a 3 2 b 3 3 c 3 4 d
1
基于多个属性分组求和。
我们在原有的数据上加上一列,可以看看多属性分组。
type_2 <-c("F","M","M","F","F","M","M","F","M","M") df <- data.frame(df, type_2
) df type value type_2 1 a 53 F 2 b 15 M 3 c 8 M 4 a 99 F 5 c 76 F 6 d 22 M 7 b
46 M 8 a 56 F 9 c 34 M 10 b 54 M aggregate(x=df$value, by=list(df$type,df$type_2
),sum) Group.1 Group.2 x 1 a F 208 2 c F 76 3 b M 115 4 c M 42 5 d M 22