我正在尝试在一个函数中使用 ez 包中的 ezANOVA,我希望允许使用参数指定 dv。通常,ezANOVA 将接受列变量作为符号或字符串(参见下面的“This Works”)。但是,尝试为 ezANOVA 提供一个包含符号或字符的参数不起作用(请参阅下面的“这不起作用”)。ezANOVA 抱怨'"the_dv" 不是提供的数据框中的变量'。我试过用 as.symbol()、as.formula() 等各种方法包装变量名,甚至尝试了各种方法来合并 eval() 和替换 (),但都没有运气。这是如何实现的?
如果它的原因有帮助,我有一个项目,我需要对数据集或正在分析的变量进行许多相同的复合分析(均值、方差分析、事后、图形)。我想要一个函数,这样我就可以编写一次并多次运行它。下面的代码只是一个简单的例子。
library(ez)
df<-data.frame(ID=as.factor(101:120),
Training=rep(c("Jedi", "Sith"), 10),
Wins=sample(1:50, 20),
Losses=sample(1:50, 20))
# ----------
# This Works
# ----------
myfunc1 <- function(the_data) {
ezANOVA(
data = the_data,
wid = ID,
dv = Wins,
between = Training
)
}
myfunc1(the_data = df)
# ------------------
# This Does Not Work
# -------------------
myfunc2 <- function(the_data, the_dv) {
ezANOVA(
data = the_data,
wid = ID,
dv = the_dv,
between = Training
)
}
myfunc2(the_data = df, the_dv = Wins) # 'Wins' also fails
Run Code Online (Sandbox Code Playgroud)
不得不自己解决这个问题。结果证明 eval() 和替换 () 的组合解决了这个难题:
# ----------------------------------
# Aha, it works!
# ----------------------------------
library(ez)
df<-data.frame(ID=as.factor(101:120),
Training=rep(c("Jedi", "Sith"), 10),
Wins=sample(1:50, 20),
Losses=sample(1:50, 20))
myfunc2 <- function(the_data, the_dv) {
eval(
substitute(
ezANOVA(data = the_data,
wid = ID,
dv = the_dv,
between = Training),
list(the_dv = the_dv)))
}
myfunc2(the_data = df, the_dv = 'Wins')
myfunc2(the_data = df, the_dv = 'Losses')
Run Code Online (Sandbox Code Playgroud)
享受!!