我有一个数据帧,看起来像这样:
pred1 pred2 pred3 exp
a b c 0
a d c 0
a b c 1我想要做的是首先获得pred1-3的所有唯一组合,将它们写到一个附加表中,为每个组合的频率添加一列,并为每个组合添加另一列,该列给出了exp的值1的比例(只能是0或1)。如下所示:
pred1 pred2 pred3 freq exp_prop
a b c 2 0.5
a d c 1 0事实证明,使用plyr的前三步非常简单:
ddply(df, .(pred1, pred2, pred3), summarise, freq=length(exp))或更短
count(df[,c(pred1, pred2, pred3)])但我就是想不出怎么才能得到exp的比例。
发布于 2012-11-17 21:13:29
您就快完成了。只需在ddply命令中添加exp_prop = mean(exp):
ddply(df, .(pred1, pred2, pred3), summarise,
freq = length(exp), exp_prop = mean(exp))
pred1 pred2 pred3 freq exp_prop
1 a b c 2 0.5
2 a d c 1 0.0发布于 2012-11-17 19:53:37
# read in your data
x <-
read.table(text="pred1 pred2 pred3 exp
a b c 0
a d c 0
a b c 1" , h = T)
library(sqldf)
sqldf( "select pred1, pred2, pred3, count(*) as numtimes, avg( exp ) as prop from x group by pred1, pred2, pred3" )
###### alternative:
# write all the column names according to some pattern
cols <- paste0("pred" , 1:3 , collapse = "," )
# save your data frame to another object
y <-
sqldf(
paste(
"select" ,
cols ,
" , count(*) as numtimes, avg( exp ) as prop from x group by" ,
cols
)
)
# print to screen
yhttps://stackoverflow.com/questions/13430203
复制相似问题