0

我正在努力在函数中使用 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")
4

1 回答 1

2

不要summarize用于此:

myddply <- function(x){
  res <- ddply(dat, .(g), 
                 function(df) setNames(t.test(df[,x])$conf.int[1], "m.ll"))
  return(res)
}
于 2013-09-16T08:53:13.143 回答