简体   繁体   English

将变量名称的函数参数传递到R函数的公式中?

[英]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. 我正在寻找一种简单的方法,将变量名称的函数参数传递到R函数的公式中。

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 ? 如果目标是创建通用函数invinteract来解决上述问题,并使用任意变量名和数据集,那么将变量名从function()参数传递到与outalfabeta

Inserting the raw variable names into the formulae does not work, because R tries to evaluate the names as objects and finds nothing. 将原始变量名称插入公式中不起作用,因为R试图将名称作为对象求值,但一无所获。

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? 是否需要使用paste()重构公式,还是有更直接的方法?

glm also accepts a character string instead of a formula. glm还接受字符串而不是公式。 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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