I'm trying to use ezANOVA from the ez package within a function where I want to allow the dv to be specified using a parameter. Normally, ezANOVA will accept the column variable as a symbol or character string (see "This Works" below). However, trying to give ezANOVA a parameter that holds a symbol or character doesn't work (see "This Does Not Work" below). ezANOVA complains that '"the_dv" is not a variable in the data frame provided'. I've tried wrapping the variable name in various methods like as.symbol(), as.formula(), and even tried various ways to incorporate eval() and substitute(), but all with no luck. How is this achieved?
If the why of it helps, i have an project where I need to do many compound analyses (means, anovas, post-hocs, graphs) that are identical expect for the dataset or the variable being analyzed. I want a function so I can write it once and run it many times. The code below is just a simple example.
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
Had to solve this one myself. Turns out that a combination of eval() and substitute() solves this puzzle:
# ----------------------------------
# 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')
Enjoy!!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments