首页 > 解决方案 > 如何正确提供数据更新功能?

问题描述

让我们考虑执行 logit 或 probit 回归的函数:

my_glm <- function(y, x, model_type = "logit") {
  do.call("glm", c(list(
    formula = y ~ ., data = base::quote(as.data.frame(x)),
    family = quote(binomial(link = model_type))
  )))
}

(我知道这个功能是以非常奇怪的方式构建的,但它在我更大的功能的一部分中扮演着非常重要的角色)

现在让我们使用人工数据和函数来拟合模型my_glm

set.seed(42)
y <- sample(0:1, 100, T)
df <- data.frame("Exp" = rexp(100), "Norm" = rnorm(100))
my_model <- my_glm(y, df)

我想要的是一个函数,它对来自函数的模型进行似然比检验my_model

到目前为止我的工作

因为我的函数my_glm是使用do.call函数创建的,所以我不能将此函数编码为:

#Incorrect!

library(lmtest)
test_model <- function(model) {  
   lrtest(model)
}

我必须使用功能update。因此,在链接功能上执行此操作非常简单:

# Link function correct
# Problem: Missing data

library(lmtest)
test_model <- function(model) {
  if (model$family$link == "logit") {
    test <- lrtest(update(model, family = binomial("logit")))
  }
  else if (model$family$link == "probit") {
    test <- lrtest(update(model, family = binomial("probit")))
  }
  test
}

但是我仍然不知道如何通过数据更新我的模型。我试图更换

test <- lrtest(update(model, family = binomial("logit"))) 

经过

test <- lrtest(update(model, family = binomial("logit"), data = model$model[-1])) 

但它不起作用。有什么方法可以正确更新此模型以便lrtest可以执行?

编辑

尼古拉评论后的当前代码:

test_model <- function(model) {
  if (model$family$link == "logit") {
    test <- lrtest(update(model, family = binomial("logit"), data = model$model[-1]))
  }
  else if (model$family$link == "probit") {
    test <- lrtest(update(model, family = binomial("probit"), data = model$model[-1]))
  }
  test
}

尝试运行时my_model

test_model(my_model)

我得到错误:

Error: node stack overflow
Error during wrapup: node stack overflow 

另一个尝试(更简单的一个):

test_model <- function(model) {
    test <- lrtest(update(model, family = binomial("logit"), data = model$model[-1]))
}

test_model(my_model)

 Error in is.data.frame(data) : object 'model' not found 

标签: rmodelregression

解决方案


推荐阅读