2

我有一个看起来像这样的数据框:

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 的比例。

4

2 回答 2

1

你快完成了。只需添加exp_prop = mean(exp)ddply命令:

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-17T13:13:29.040 回答
0
# 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
y
于 2012-11-17T11:53:36.777 回答