从R中的分组数据框计算性别百分比

时间:2013-12-07 15:40:43

标签: r grouping

我有相当大的数据框,其中包含分为治疗组的个人信息。我试图为每个组生成可变的均值和性别百分比。我能够计算出手段,但我不确定如何获得性别百分比。

下面,我为我的数据生成了一个小型副本:

library(plyr)
#create variables and data frame
sampleid<-seq(1:100)
gender = rep(c("female","male"),c(50,50))
score <- rnorm(100)
age<-sample(25:35,100,replace=TRUE)
treatment <- rep(seq(1:5), each=4)
d <- data.frame(sampleid,gender,age,score, treatment)

>head(d)

  sampleid gender age      score treatment
1        1 female  34  1.6917201         1
2        2 female  26 -1.6189545         1
3        3 female  28  1.2867895         1
4        4 female  34 -0.5027578         1
5        5 female  29 -1.3652895         2
6        6 female  26 -2.4430843         2

我通过以下方式获得每个数字列的平均值:

groupstat<-ddply(d, .(treatment),numcolwise(mean))

给出:

  treatment sampleid   age        score
1         1     42.5 29.15  0.142078574
2         2     46.5 29.50 -0.261492514
3         3     50.5 30.50 -0.188393235
4         4     54.5 30.45  0.003526078
5         5     58.5 30.55  0.062996737

然而,我还需要一个额外的栏目“百分比女性”,这应该给我每个治疗组1:5中女性的百分比。 有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

试试这个

groupstat<-ddply(d, .(treatment),summarise,
                 meansc= mean(score),
                 meanage= mean(age),
                 meanID= mean(sampleid),
                 nfem= length(gender[gender=="female"]), # number females per treatment group
                 nmale= length(gender[gender=="male"]), # number of males per treatment group
                 percentfem= nfem/(nfem+nmale)) # percent females by treatment group

答案 1 :(得分:1)

我首先会分成治疗组(split(d, f = d$treatment))而不是计算每组的方法(function(x) sum(x$gender == "female")/length(x$gender)

sapply(split(d, f = d$treatment), function(x) sum(x$gender == "female")/length(x$gender))