How to use a symbol as an attribute of a function

I want to perform an analysis of several comparisons for different model variables. My idea is this:

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, you cannot use a character to indicate an attribute of the mcp function. Does anyone know a solution?

+4
source share
3 answers

( Update: Make sure Hadley is responsible for the best way to do this, without resorting to inserting lines. My answer will still be helpful in explaining why this is more complicated than usual in this case.)

The features of mcp() require a relatively brute force approach to glue the expression you want to evaluate, and then pass it through eval(parse()) .

The mcp() bit is that mcp() interprets its first argument in a non-standard way. Within mcp() , x1 = 'Tukey' does not mean (as it usually was) "assign the value of 'Tukey' argument x1 ." Instead, all of this is interpreted as a symbolic description of the alleged contrasts. (In this, it looks like more familiar formula objects, such as y ~ x1 + x2 in your lm() call).

 for(var in c('x1', 'x2')) { # Construct a character string with the expression you'd type at the command # line. For example : "mcp(x1 = 'Tukey')" exprString <- paste("mcp(", var, "='Tukey')") # eval(parse()) it to get an 'mcp' object. LINFCT <- eval(parse(text = exprString)) mc1 <- glht(fm1, linfct = LINFCT) print(summary(mc1)) } 
+3
source

As a rule, it is better to avoid working with lines representing the code where possible - this prevents errors that are difficult to debug, and aesthetically much more elegant. This problem turns out to be pretty easy to solve if you use the do.call and setNames :

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

You cannot use substitute here because it does not allow changing function parameter names. I have an intuition why this is reasonable, but not enough to explain this: /

If you are the author of the package, it’s nice to provide an alternative version of functions that use unusual syntax so that you can get them programmatically without jumping over hoops.

+13
source

Have you tried: eval(parse(text='variable')) or assign ?

+2
source

Source: https://habr.com/ru/post/1385567/


All Articles