library(lme4)
dummy <- as.data.frame(cbind(speed = rpois(100, 10), pop = rep(1:4, each = 25), season = rep(1:2, each = 50), id = seq(1, 100, by = 1)))
dummy2 <- as.data.frame(cbind(speed = c(rnbinom(50, 10, 0.6), rnbinom(50, 10, 0.1)), pop = rep(1:4, each = 25), season = rep(1:2, each = 50), id = seq(1, 100, by = 1)))
poisson <- glmer(speed~pop*season + (1|id),
data=dummy, family="poisson")
neg.bin <- glmer.nb(speed ~ pop*season + (1|id),
data=dummy2, control=glmerControl(optimizer="bobyqa"))
When I run a script creating a Poisson model before a negative binomial model using the lme4 package, I get the following error when running the neg.bin model:
Error in family$family : $ operator not defined for this S4 class
However, if I run the models in the opposite order, I don't the error message.
library(lme4)
dummy <- as.data.frame(cbind(speed = rpois(100, 10), pop = rep(1:4, each = 25), season = rep(1:2, each = 50), id = seq(1, 100, by = 1)))
dummy2 <- as.data.frame(cbind(speed = c(rnbinom(50, 10, 0.6), rnbinom(50, 10, 0.1)), pop = rep(1:4, each = 25), season = rep(1:2, each = 50), id = seq(1, 100, by = 1)))
neg.bin <- glmer.nb(speed ~ pop*season + (1|id),
data=dummy2, control=glmerControl(optimizer="bobyqa"))
poisson <- glmer(speed~pop*season + (1|id),
data=dummy, family="poisson")
The neg.bin model example does have convergence warnings, but the same pattern is happening with my actual models which are converging fine. How is running the Poisson model first affecting the neg.bin model?
Because you have masked R function poisson
. The following would work fine (except that there is convergence warning for neg.bin
):
library(lme4)
set.seed(0)
dummy <- as.data.frame(cbind(speed = rpois(100, 10), pop = rep(1:4, each = 25), season = rep(1:2, each = 50), id = seq(1, 100, by = 1)))
dummy2 <- as.data.frame(cbind(speed = c(rnbinom(50, 10, 0.6), rnbinom(50, 10, 0.1)), pop = rep(1:4, each = 25), season = rep(1:2, each = 50), id = seq(1, 100, by = 1)))
## use a different name for your model, say `poisson_fit`
poisson_fit <- glmer(speed~pop*season + (1|id),
data=dummy, family="poisson")
negbin_fit <- glmer.nb(speed ~ pop*season + (1|id),
data=dummy2, control=glmerControl(optimizer="bobyqa"))
Here is the issue. Among the very first few lines of glmer.nb
there is one line:
mc$family <- quote(poisson)
So, if you mask poisson
, correct function poisson
from stats
package can not be found.
Ben has just fixed this issue, by replacing this to:
mc$family <- quote(stats::poisson)
My original observation on family = "poisson"
and match.fun
stuff is not the real issue here. It only explains why in routines like glm
and mgcv::gam
, it is legitimate to pass a string of family
.
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