简体   繁体   中英

Pass function arguments that are variable names into formulae in R functions?

I am looking for a simple way to pass function arguments that are variable names into formulae in R functions.

Test dataset:

set.seed(4892)
df.pass <- data.frame("alfa"=sample(1:9, 100, replace=T), "beta"=sample(1:9, 100, replace=T), 
                      "theta"=sample(1:9, 100, replace=T), "out"=runif(100, 0, 1))

Example analysis (testing if interaction model is different) to be made into function:

lrtest(glm(out~alfa*beta, family = binomial("logit"), df.pass),
       glm(out~alfa + beta, family = binomial("logit"), df.pass))

If the goal is to create the generic function invinteract that solves the problem above with arbitrary variable names and data sets, what would be the simplest way to pass variable names from function() arguments to formulae terms corresponding to the positions of out , alfa and beta ?

Inserting the raw variable names into the formulae does not work, because R tries to evaluate the names as objects and finds nothing.

Inserting string variable names directly into formulae does not work either.

Is it necessary to reconstruct the formulae with paste() , or is there a more direct way?

glm also accepts a character string instead of a formula. Thus, you can do this:

mytest <- function(DF, y, x1, x2) {
  lrtest(glm(sprintf("%s ~ %s * %s", y, x1, x2), family = binomial("logit"), DF),
         glm(sprintf("%s ~ %s + %s", y, x1, x2), family = binomial("logit"), DF))
}
mytest(df.pass, "out", "alfa", "beta")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM