r - 如何正确提供数据更新功能?
问题描述
让我们考虑执行 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
解决方案
推荐阅读
- tcl - 获取包含子字符串的最后一次出现的行
- ios - 是否可以复制 iOS 表情符号键盘的搜索栏?与自定义键盘应用程序中的常规文本框不同,您可以在 iOS 表情符号中切换语言
- javascript - 如何使用 safari 从 iPhone 连接到本地服务器?
- c++ - C++ 打印 AVL 树元素时删除最后一个逗号
- python - Elastic Beanstalk 的 Python 打印语句输出
- python - 如何在 Python Regex Dataframe 中删除多种特殊字符模式
- python - 在 PyCharm 中设置虚拟环境时出现错误:Error: [WinError 2] The system can't find the files
- python-3.x - 我的 BST 函数查找左子树的最大元素和右子树的最小元素不会返回值
- gitlab - 在更改 external_url 时出现此 gitlab 错误
- python - 如何创建具有某些权限的组