示例:具有许多个人和 3 个变量的数据框:年份(整数)、性别(因子:男/女)和工会(因子:是/否)。我想计算在给定年份和性别的情况下成为工会成员的概率。我通常用聚合()来做到这一点。我是否一直在这样做,我正在寻找一种在 dplyr 中快速快速的方法。
亲切的问候,彼得
这dplyr
相当于@droopy的答案:
tbl_df( x ) %.%
group_by( year, gender ) %.%
summarise( P = mean(union == "yes") )
Source: local data frame [8 x 3]
Groups: year
year gender P
1 2001 female 1.0
2 2001 male 0.5
3 2002 female 0.5
4 2002 male 0.0
5 2003 female 0.0
6 2003 male 0.5
7 2004 female 0.5
8 2004 male 0.0
...为了完整起见,还有data.table
解决方案:
as.data.table(x)[ , list( P = mean( union == "yes" ) ), by = list( year, gender ) ]
year gender P
1: 2001 male 0.5
2: 2001 female 1.0
3: 2002 male 0.0
4: 2002 female 0.5
5: 2003 male 0.5
6: 2003 female 0.0
7: 2004 male 0.0
8: 2004 female 0.5
类似的东西?
x <- data.frame(year=rep(2001:2004, each=4), gender=rep(c("male", "female"), 8), union=sample(c("yes", "no"), 16, rep=T))
ddply(x, .(year, gender), summarize, P=mean(union=="yes"))