glm.fit的内部结构已经改变(请参见@John的评论),因此请使用此替代方法。它不依赖于内部结构的行位置,而是在glm.fit中截获每个cat实例并将消息添加到迭代消息中,因此尽管它仍然依赖于内部结构,但应该更加稳定。在R 4.1和4.2中对我有效。
library(MASS)
data(menarche)
trace(glm.fit, quote(cat <- function(...) {
base::cat(...)
if (...length() >= 3 && identical(..3, " Iterations - ")) print(coefold)
}))
glm.out = glm(cbind(Menarche, Total-Menarche) ~ Age,
family=binomial(logit), data=menarche,
control = glm.control(trace = TRUE))
untrace(glm.fit)
之前的解决方案
使用值为所示的control=
参数会导致偏差打印,使用trace
语句将导致系数值打印:
trace(glm.fit, quote(print(coefold)), at = list(c(22, 4, 8, 4, 19, 3)))
glm.out = glm(cbind(Menarche, Total-Menarche) ~ Age,
family=binomial(logit), data=menarche,
control = glm.control(trace = TRUE))
输出结果将类似于:
Tracing glm.fit(x = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, .... step 22,4,8,4,19,3
NULL
Deviance = 27.23412 Iterations - 1
Tracing glm.fit(x = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, .... step 22,4,8,4,19,3
[1] -20.673652 1.589536
Deviance = 26.7041 Iterations - 2
Tracing glm.fit(x = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, .... step 22,4,8,4,19,3
[1] -21.206854 1.630468
Deviance = 26.70345 Iterations - 3
Tracing glm.fit(x = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, .... step 22,4,8,4,19,3
[1] -21.226370 1.631966
Deviance = 26.70345 Iterations - 4
要删除痕迹,请使用:
untrace(glm.fit)
请注意,在trace
调用中,coefold
是在glm.fit
源代码中内部使用的变量名称,并且使用的数字是指源代码中的语句编号,因此如果glm.fit
源代码发生更改,则这些数字可能需要更改。我正在使用“R版本3.2.2 Patched(2015-10-19 r69550)”。
glm.fit
源代码发生更改,则两者都可能需要更改:我认为在4.1左右可能已经发生了这种情况,因为该命令开始返回错误。 - John