在函数和ddply中引用列名

时间:2015-04-15 19:21:00

标签: r reference plyr

我正在尝试创建一个使用ddply来汇总我传入的特定列的数据的函数。我能够在ddply之外引用我想要的列,但我不知道该怎么做在ddply内:

exp_group = c('test','test','control','control')
value = c(1,3,2,3)

df <- data.frame(exp_group, value)

compare_means <- function(df,cols_detail, col_to_eval){
    df_int <- df[, c(cols_detail, col_to_eval)] # this part works fine

    summary <- ddply(df_int
                  , .(exp_group)
                  , summarize
                  , mean = t.test(col_to_eval)$estimate #these ones don't
                  , lo_bound = t.test(col_to_eval)$conf.int[1]
                  , hi_bound = t.test(col_to_eval)$conf.int[2]
                  )

  return(summary)
}

test <- compare_means(df, 'exp_group','value')

当我这样做时,它返回找不到col_to_eval。我还尝试使用df_int [,col_to_eval]以及df_int [,2](col参考值),并说它找不到df_int。

我想找到测试组和控制组的方法。

如何在t.test函数中引用我想要的列?

1 个答案:

答案 0 :(得分:1)

好的,经历了几次迭代,最后通过这样做得到了它:

exp_group = c('test','test','control','control')
value = c(1,3,2,3)

df <- data.frame(exp_group, value)

compare_means <- function(df,cols_detail, col_to_eval){
  df_int <- df[, c(cols_detail, col_to_eval)]

  summary <- ddply(df_int
                   , .(exp_group)
                   , function(x){
                     mean = t.test(x[,col_to_eval])$estimate
                     lo_bound = t.test(x[,col_to_eval])$conf.int[1]
                     hi_bound = t.test(x[,col_to_eval])$conf.int[2]
                     data.frame(mean, lo_bound, hi_bound)
                   }
  )

  return(summary) 
}

test <- compare_means(df, 'exp_group','value')