I'm doing a one-way anova and post-Hoc multiple comparison. Using mtcars dataset as an example:
mtcars$cyl <- as.factor(mtcars$cyl)
aov<- aov(mpg~cyl, data=mtcars)
summary(multcomp::glht(aov, linfct=mcp(cyl='Dunnet')))
However, I do not want to hardcode the variable as cyl. so I create a variable var='cyl':
var <- 'cyl'
aov <- aov(as.formula(paste('mpg~', var)), data=mtcars)
summary(multcomp::glht(aov, linfct=mcp( var='Dunnet')))
I got error message:
Error in mcp2matrix(model, linfct = linfct) : Variable(s) ‘var’ have been specified in ‘linfct’ but cannot be found in ‘model’!
I think the problem comes from passing var in the mcp function. How can I fix this? I tried: as.name(var) , eval(quote(var))... But no luck.. Thanks a lot for help.
We could use the do.call
approach
aov1 <- do.call("aov", list(formula = as.formula(paste('mpg~', var)), data = quote(mtcars)))
out2 <- summary(multcomp::glht(aov1, linfct = do.call(mcp, setNames(list("Dunnet"), var))))
Checking with the output in the OP's post
out1 <- summary(multcomp::glht(aov, linfct=mcp(cyl='Dunnet')))
all.equal(aov, aov1)
#[1] TRUE
all.equal(out1, out2)
#[1] TRUE
The above can be wrapped in a function
f1 <- function(dat, Var){
form1 <- formula(paste('mpg~', Var))
model <- aov(form1, data = dat)
model$call$formula <- eval(form1)
model$call$data <- substitute(dat)
summary(multcomp::glht(model, linfct = do.call(mcp, setNames(list("Dunnet"), Var))))
}
f1(mtcars, var)