Reputation:
I have a function implementing the Fisher algorithm in R for a GLM which takes formula as an argument. However when attempting to run it I get the error: Error in model.frame.default(formula = formula, drop.unused.levels = TRUE) : invalid type (closure) for variable 't'
I tried calling it in several ways (e.g using as.formula(y~t)
but nothing seems to work.
myglm <- function(formula,data,start = 0) {
X = model.matrix(formula,data) #It appears that the issue comes from this line
Y = data[,1]
n = dim(X)[1]
p <- dim(X)[2]
beta_0 = rep(1,p)
M = t(X)%*%X
beta = rep(0,p)#Least Squares Estimate
epsilon = 0.01
#Run Fisher Iterations
while (norm(beta-beta_0,type = "2")/norm(beta_0, type = "2") > epsilon) {
beta_0 = beta
eta = X %*% beta
lambda = exp(eta)
F = t(X) %*% diag(as.vector(lambda)) %*% X #Fisher information matrix
s = t(X) %*% (Y - exp(eta)) #Score function
beta = beta + solve(F) %*% s
}
vcov = solve(F)
coef = matrix(c(0,0,0,0),nrow = 2, ncol = 2)
coef[,1] = beta
coef[,2] = t(sqrt(diag(vcov)))
colnames(coef) = c("Coefficients","Standard error")
rownames(coef) = c("beta1", "beta2")
#Calculate Deviance
mod_sat = glm(formula, family = poisson(link = "log"))
log_likelihood = Y %*% eta - exp(eta)
deviance = 2*(LogLik(mod_sat) - log_likelihood)
return(list(coef,deviance,vcov))
}
f = formula(y ~ t)
load(url("https://www.math.ntnu.no/emner/TMA4315/2020h/hoge-veluwe.Rdata")) #This is stored as "data"
myglm(f, data)
Upvotes: 1
Views: 51
Reputation: 5747
Your issue is in this line:
mod_sat = glm(formula, family = poisson(link = "log"))
You need to specify a data =
argument to glm()
so it knows how to interpret the formula.
Upvotes: 1