【问题标题】:Get unique value combinations with summary count of another variable获取具有另一个变量汇总计数的唯一值组合
【发布时间】:2012-11-17 11:38:46
【问题描述】:

我有一个如下所示的数据框:

pred1 pred2 pred3 exp
a     b     c     0
a     d     c     0
a     b     c     1

我想做的是首先获取pred1-3的所有唯一组合,将它们写入一个附加表,为每个组合的频率添加一列,并添加另一列给出值1的比例每个组合的 exp(只能是 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 的比例。

【问题讨论】:

    标签: r dataframe plyr summary


    【解决方案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
    

    【讨论】:

      【解决方案2】:
      # 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
      

      【讨论】:

      • 嘿,这很快 - 非常感谢!不幸的是,我的电脑上似乎没有运行 sqldf 包。加载它可以工作,但是一旦我输入任何命令,我就会收到一条消息,说“捕获总线错误”并且 R 崩溃。难道没有办法用原生 R 语法做到这一点吗?
      • 假设您使用的是 mac?安装它,它会工作。 sqldf 是一个了不起的包。 r.789695.n4.nabble.com/…
      猜你喜欢
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 2020-07-12
      • 2021-07-24
      相关资源
      最近更新 更多