When I use an object that stores the link function for the MASS package's glm.nb function, the function errors out. However, when I just hard-code the link function, it works fine. I think this has to be due to some sort of environmental referencing gone wrong in their source code, but wanted to be certain before emailing the authors. So, any insight is appreciated here.
MWE
# Simulate some data
set.seed(666)
n = 1000
x = cbind(1, rnorm(n))
b = c(1,-2)
lam = exp(x%*%b)
y = rnbinom(n, size=.3, mu = lam)
# get package
if(!("MASS" %in% rownames(installed.packages()))
install.packages("MASS")
library(MASS)
Attempt 1 -- Define link as parameter default
# Define some wrapper function around glm.nb
mfn = function(y, x, mylink = "log"){
MASS::glm.nb(y ~ x - 1, link=mylink)
}
# Call mfn on simulated data
mfn(y, x)
> Error in poisson(link = mylink) : object 'mylink' not found
# Call with explicit link in mfn
mfn(y = y, x = x, mylink="log")
> Error in poisson(link = mylink) : object 'mylink' not found
Attempt 2 -- Modifying mfn to define mylink in function environment
# Redefine function
mfn = function(y, x){
mylink = "log"
MASS::glm.nb(y ~ x - 1, link=mylink)
}
# Call on simulated data
mfn(y = y, x = x)
> Error in poisson(link = mylink) : object 'mylink' not found
Attempt 3 Combine (1) and (2)
# Redefine mfn
mfn = function(y, x, mylink = "log"){
mylink = "log"
MASS::glm.nb(y ~ x - 1, link = mylink)
}
mfn(y = y, x = x, mylink="log")
> Error in poisson(link = mylink) : object 'mylink' not found
Just to be sure -- Hard-code link function
mfn = function(y, x){
mylink = "log"
MASS::glm.nb(y ~ x - 1, link="log")
}
mfn(y = y, x = x)
> Call: MASS::glm.nb(formula = y ~ x - 1, link = "log", init.theta = 0.2953628307)
Coefficients:
x1 x2
0.9415 -1.9165
Degrees of Freedom: 1000 Total (i.e. Null); 998 Residual
Null Deviance: 6191
Residual Deviance: 853.8 AIC: 4248
So its pretty clear that there is some sort of referencing issue going on, but I can't immediately find it in the source code nor do I know of a simpler way to test the issue. Any ideas?