我正在尝试编写一个使用公式表达式的模型构建函数,但在理解模型 update
时遇到一些问题功能有效。
这是一个精简函数,在使用 update
时会导致错误功能:
modelx <- function(formula) {
mf <- mc <- match.call()
mf <- mf[c(1L, match("formula", names(mf), 0L))]
mf[[1L]] <- as.name("model.frame")
mf <- eval(mf, parent.frame())
y <- model.response(mf, "numeric")
mt <- attr(mf, "terms")
X <- model.matrix(mt, mf)
out<-list(y=y,X=X)
out$call<-mc
out
}
代码几乎是从 lm
的开头复制的。功能。一些示例数据和两个模型:
y<-x<-x1<-x2<-1:10
model<-modelx(y ~ x)
model1<-modelx(y ~ x1)
现在更新第一个模型不起作用,但第二个模型可以:
model<-update(model, . ~ . + x2)
Error in model.frame.default(formula = y ~ x + x2) :
invalid type (list) for variable 'x'
model1<-update(model1, . ~ . + x2)
如果我添加一个组件out$terms <- mt
进入 modelx
的输出,在这两种情况下一切都有效。为什么需要这个组件?为什么在第二种情况下更新功能可以在没有它的情况下工作,但在第一种情况下却不能?
最佳答案
如果您查看 update
(?update
) 的帮助,它会告诉您:
Description
update will update and (by default) re-fit a model. It does this by extracting the call stored in the object, updating the call and (by default) evaluating that call. Sometimes it is useful to call update with only one argument, for example if the data frame has been corrected.
“Extracting the call” in update() and similar functions uses getCall() which itself is a (S3) generic function with a default method that simply gets x$call.
Because of this, update() will often work (via its default method) on new model classes, either automatically, or by providing a simple getCall() method for that class.
Usage
update(object, ...)
getCall(x, ...)
在我看来,冲突正在发生,因为信息正在传递到 getCall
函数,其中 x
是参数的名称,然后会经历一个名称与您的 x
发生冲突,并且该语言选择本地 x
而不是您的 x
。
关于使用名为 'x' : 的变量时更新公式时出现 R 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15202218/