【发布时间】:2013-12-07 15:40:43
【问题描述】:
我有相当大的数据框,其中包含有关按治疗组划分的个人的信息。我正在尝试为每组生成可变均值和性别百分比。我能够计算平均值,但我不确定如何获得性别百分比。
下面,我生成了我的数据的一个小副本:
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。 有人可以帮我添加这个吗?
【问题讨论】:
-
创建另一个变量,女性 = 1,男性 = 0。取其平均值。