成语中的plyr
包装和ddply
特别是,它与 Excel 中的数据透视表非常相似。
在您的示例中,您唯一需要做的就是cut
在传递到之前,将变量分组到所需的中断中ddply
。这是一个例子:
首先,创建一些示例数据:
set.seed(1)
dat <- data.frame(
userid = 1:500,
visits =sample(0:50, 500, replace=TRUE),
posts = sample(0:50, 500, replace=TRUE),
revenue = sample(1:100, replace=TRUE)
)
现在,使用cut
将分组变量划分为所需的范围:
dat$PostRange <- cut(dat$posts, breaks=seq(0, 50, 10), include.lowest=TRUE)
dat$VisitRange <- cut(dat$visits, breaks=seq(0, 50, 10), include.lowest=TRUE)
最后,使用ddply
with summarise
:
library(plyr)
ddply(dat, .(VisitRange, PostRange),
summarise,
Users=length(userid),
`Total Revenue`=sum(revenue),
`Average Revenue`=mean(revenue))
结果:
VisitRange PostRange Users Total Revenue Average Revenue
1 [0,10] [0,10] 23 1318 57.30435
2 [0,10] (10,20] 23 1136 49.39130
3 [0,10] (20,30] 28 1499 53.53571
4 [0,10] (30,40] 20 923 46.15000
5 [0,10] (40,50] 14 826 59.00000
6 (10,20] [0,10] 23 1227 53.34783
7 (10,20] (10,20] 17 642 37.76471
8 (10,20] (20,30] 20 888 44.40000
9 (10,20] (30,40] 15 622 41.46667
10 (10,20] (40,50] 21 968 46.09524
11 (20,30] [0,10] 23 1226 53.30435
12 (20,30] (10,20] 19 1021 53.73684
13 (20,30] (20,30] 23 1380 60.00000
14 (20,30] (30,40] 8 313 39.12500
15 (20,30] (40,50] 19 710 37.36842
16 (30,40] [0,10] 18 782 43.44444
17 (30,40] (10,20] 25 1308 52.32000
18 (30,40] (20,30] 14 553 39.50000
19 (30,40] (30,40] 26 1131 43.50000
20 (30,40] (40,50] 20 1295 64.75000
21 (40,50] [0,10] 20 958 47.90000
22 (40,50] (10,20] 21 1168 55.61905
23 (40,50] (20,30] 20 1118 55.90000
24 (40,50] (30,40] 20 1009 50.45000
25 (40,50] (40,50] 20 934 46.70000