如何在R函数中使用逻辑回归

How to use logistic regression in R function

我正在尝试在我的自定义 r 函数中使用 r 基本逻辑回归函数,但我的 glm() 无法识别我的变量。我在搜索引擎中尝试了多个搜索关键字,但所有答案都与拟合逻辑回归有关。

例如:

第一次尝试:

dat <- data.frame(a = c(3,4,5), b = c("a","a","b"))

logit <- function(dataname, x, y) {
  model = glm(y ~ x, data = dataname, family = "binomial")
  model
}

logit(dat, a, b)
Error in eval(predvars, data, env) : object 'b' not found

另一种方式:

logit <- function(dataname, x, y) {
  model = glm(eval(substitute(y), dat) ~ eval(substitute(x), dat), family = "binomial")
  model
}

logit(dat, a, b)

输出会将我的 IV 更改为 eval(substitute(x), dataname) 而不是 x。

glm.fit: fitted probabilities numerically 0 or 1 occurred
Call:  glm(formula = eval(substitute(y), dataname) ~ eval(substitute(x), 
    dataname), family = "binomial")

Coefficients:
                  (Intercept)  eval(substitute(x), dataname)  
                      -208.27                          46.34  

Degrees of Freedom: 2 Total (i.e. Null);  1 Residual
Null Deviance:      3.819 
Residual Deviance: 3.597e-10    AIC: 4

有什么方法可以在输出中使用正确的 IV 名称获得正确的输出?

谢谢

logit <- function(dataname, x, y) {
  model = glm( as.formula(paste(y,  "~", x)),
               data = dataname,
               family = "binomial")
  model
}

logit(dat, "a", "b")

如果你有很多解释变量,你可以传入一个名称向量并使用:

as.formula(paste(y,  "~", paste(x, collapse="+")))

我同意@IceCreamToucan 的观点,最好的方法是将公式传递给函数

logit <- function(dataname, formula) {
  model = glm(formula, data = dataname, family = "binomial")
  model
}

logit(dat, b~a)

否则你应该先构建公式,然后将它传递给 glm

logit <- function(dataname, x, y) {
  formula <- reformulate(as.character(substitute(x)), as.character(substitute(y)))
  model = glm(formula, data = dataname, family = "binomial")
  model
}

logit(dat, a, b)