将作为变量名的函数参数传递给 R 函数中的公式?

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

我正在寻找一种简单的方法来将作为变量名的函数参数传递给 R 函数中的公式。

测试数据集:

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))

实例分析(测试交互模型是否不同)做成函数:

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

如果目标是创建通用函数 invinteract 来解决上述带有任意变量名和数据集的问题,那么将变量名从 function() 参数传递给outalfabeta?

位置对应的公式项

将原始变量名称插入到公式中不起作用,因为 R 试图将名称作为对象求值,但没有找到任何结果。

将字符串变量名直接插入公式中也不起作用。

是否需要用paste()重构公式,还是有更直接的方法?

glm 也接受字符串而不是公式。因此,您可以这样做:

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")