I am going through a statistics textbook on my own. I am using semi-official code (from a manual written by somebody else, but linked on the textbook's site) to calculate the examples and exercises.
The code includes a function for fitting generalized linear models. I typed it from the manual and ran it as suggested. And although the actual fitting works, I get the above error when assigning labels to the results.
The line which throws the error is
names(fit$part) <- dn
At that point, the value of dn
is [1] "(Intercept)" "Var1"
and the value of fit$par
is [1] -5.9604611 0.3165604
I don't see any NULL there, and wonder what could cause the error.
The complete code is:
ct <- data.frame(alcohol.comsumption = c("0", "<1", "1-2", "3-5", ">= 6"), scores=c(0, 0.5, 1.5, 4, 7), absent = c(17066, 14464, 788, 126, 37), present = c(48, 38, 5, 1, 1))
n <- ct$absent + ct$present
alc.consumption <- rep(ct$scores, n)
y <- rep(rep(c(1,0), nrow(ct)), c(rbind(ct$present, ct$absent)))
logitreg <- function(x, y, wt = rep(1, length(y)), intercept = T, start = rep(0, p), ...)
{
if(!exists("optim")) library(MASS)
fmin <- function(beta, X, y, w) {
p <- plogis(X %*% beta)
-sum(2 * w * ifelse(y, log(p), log(1-p)))
}
gmin <- function(beta, X, y, w)
{
eta <- X %*% beta; p<-plogis(eta)
t(-2 * (w *dlogis(eta) *ifelse(y, 1/p, -1/(1-p))))%*% X
}
if(is.null(dim(x))) dim(x) <- c(length(x),1)
dn <- dimnames(x)[[2]]
if(!length(dn)) dn <- paste("Var", 1:ncol(x), sep="")
p <- ncol(x) + intercept
if(intercept) {x <- cbind(1, x); dn <- c("(Intercept)", dn)}
if(is.factor(y)) y <- (unclass(y) != 1)
fit <- optim(start, fmin, gmin, X=x, y=y, w=wt, ...)
# --- Next line throws the error --- #
names(fit$part) <- dn
cat("\nCoefficients:\n"); print(fit$par)
cat("\nResidual Deviance:", format(fit$value), "\n")
cat("\nConvergence message:", fit$convergence, "\n")
invisible(fit)
}
logit.fit<-logitreg(x=alc.consumption, y=y, hessian=T, method="BFGS")
Looks like either you or the book author mistyped names(fit$par)
as names(fit$part)
, which doesn't exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With