I’m sure I’m missing something obvious here; am trying to use a loop to change the inputs to a formula, then generate a glht involving that formula. (glht = general linear hypothesis test). Thanks all!
df2 <- data.frame(f1=seq(1:5),f2=seq(4,8), y=sample(x=c(0,1),size=5,replace=TRUE))
df2 <- data.frame(lapply(df2,factor)) # convert to factors
library(multcomp)
for (i in 1:(length(df2)-1)){
fmla <- as.formula( paste("y~",colnames(df2)[i],sep=""))
fm1 <- glm (fmla, family = binomial("logit"), data=df2)
}
This much works; now I’m trying to dynamically pass in f1 to make the line below:
tuk <- glht(fm1, linfct=mcp(f1 ="Tukey"))
I have tried:
tuk <- glht(fm1,linfct=mcp(colnames(df2)[i] ="Tukey"))
but this gives:
Error: unexpected '=' in " tuk <- glht(fm1,linfct=mcp(colnames(df2)[i] ="
I thought this would be something to do with parse/eval.
So I tried:
e1 <- paste("fm1,linfct=mcp(",colnames(df2)[i],"=Tukey)",sep="")
glht(e1)
Gives:
Error in object$coefficients : $ operator is invalid for atomic vectors
Error in modelparm.default(model, ...) : no 'coef' method for 'model' found!
Then tried:
e1 <- parse(text=paste("fm1,linfct=mcp(",colnames(df2)[i],"=Tukey)",sep="") )
glht(e1)
Gives:
Error in parse.default(text = paste("fm1,linfct=mcp(", colnames(df2)[i], :
<text>:1:4: unexpected ','
1: fm1,
^
Finally:
e1 <- as.expression(paste("fm1,linfct=mcp(",colnames(df2)[i],"=Tukey)",sep="") )
glht(e1)
Gives:
Error in UseMethod("vcov") : no applicable method for 'vcov' applied to an object of class "expression"
Error in modelparm.default(model, ...) : no 'vcov' method for 'model' found!
An essentially identical question was asked and answered on SO last year. The answer below uses the strategy outlined then by @hadley, explaining in a bit more detail why it works.
What’s tricky about this problem is that you need to pass in each column name as the name of the sole argument to
mcp(). Usingdo.call()is probably the best way to accomplish this.What you want:
How to get it when you have a variable
X="f1":In your case, you can do something like this: