Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a character as attribute of a function

I want to run a multiple comparisons analysis for the different variables of a model. My idea is as follows:

library(multcomp)
set.seed(123)
x1 <- gl(4,10)
x2 <- gl(5,2,40)
y <- rnorm(40)

fm1 <- lm(y ~ x1 + x2)

for(var in c('x1', 'x2'))
{
mc1 <- glht(fm1, linfct=mcp(var='Tukey'))
print(summary(mc1))
}

When I run, I get the following error:

Error en mcp2matrix(model, linfct = linfct) : 
    Variable(s) ‘var’ have been specified in ‘linfct’ but cannot be found in ‘model’! 

That is, it is not possible to use a character to specify an attribute of the mcp function. Anyone knows a solution?

like image 664
Manuel Ramón Avatar asked Dec 02 '22 00:12

Manuel Ramón


1 Answers

It's generally better to avoid working with strings representing code wherever possible - it prevents errors that are hard to debug, and aesthetically is much more elegant. This problem turns out to be fairly easy to solve if you use do.call and the setNames function:

var <- "x1"
cmp <- do.call(mcp, setNames(list("Tukey"), var))
glht(fm1, linfct = cmp)

You can't use substitute here because it does not allow you modify the names of function parameters. I have some intuition for why this is reasonable, but not enough to explain it :/

If you're a package author, it's a good idea to provide an alternative version of functions that use unusual syntax so they can be accessed programmatically without jumping through hoops.

like image 191
hadley Avatar answered Dec 23 '22 14:12

hadley