【问题标题】:How to use logistic regression in R function如何在 R 函数中使用逻辑回归
【发布时间】:2020-06-03 19:10:13
【问题描述】:

我正在尝试在我的自定义 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 名称获得正确的输出?

谢谢

【问题讨论】:

  • 最简单的解决方案是将公式作为您自己函数的参数之一,而不是单个变量。然后只需将公式参数传递给函数内的glm,它应该可以按预期工作。

标签: r function logistic-regression glm


【解决方案1】:

我同意@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)

【讨论】:

    【解决方案2】:
    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="+")))
    

    【讨论】:

      猜你喜欢
      • 2019-10-14
      • 2019-06-25
      • 2018-01-26
      • 1970-01-01
      • 2019-08-20
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      相关资源
      最近更新 更多