如何在函数内部使用ddply?

时间:2013-09-16 08:38:39

标签: r plyr

我正在努力在函数中使用ddly()。以下有希望说明我想要实现的目标:

library(plyr)
dat <- data.frame(var1 = rnorm(10), g = rep(1:2, 5))
dat

## Works for a particular variable "var1"
ddply(dat, .(g), summarize, m.ll = t.test(var1)$conf.int[1])

## ... but not inside a function
myddply <- function(x){
    res <- ddply(dat, .(g), summarize, m.ll = t.test(x)$conf.int[1])
    return(res)
}
myddply(x = "var1")

我认为eval(parse(...))会起作用,但无济于事。

myddply <- function(x){
    res <- ddply(dat, .(g), summarize, m.ll = t.test(eval(parse(text = x)))$conf.int[1])
    return(res)
}
myddply(x = "var1")

1 个答案:

答案 0 :(得分:2)

请勿使用summarize

myddply <- function(x){
  res <- ddply(dat, .(g), 
                 function(df) setNames(t.test(df[,x])$conf.int[1], "m.ll"))
  return(res)
}