I'd like to extract the model call for a list of models. The list includes both glm and glmm.
It seems like this works for glm objects, but not for glmerMod objects
gm1 <- glm(cbind(incidence, size - incidence) ~ period,
data = cbpp, family = binomial)
gm1$call
>glm(formula = cbind(incidence, size - incidence) ~ period, family = binomial,
data = cbpp)
gm2 <- glmer(cbind(incidence, size - incidence) ~ period (1 | herd),
data = cbpp, family = binomial)
gm2$call
>Error in gm2$call : $ operator not defined for this S4 class
I can see when I click on the glmerMod objects in the rstudio environment pane that the object does appear to have a call value associated with it.
Is there a way I could extract this information from both types of models using the same function? This would be my preference becasue I'm hoping to set it up as an lapply function to apply to a list of models.
models <- list(gm1, gm2)
calls <- lapply(models, function(x) x$call)
CodePudding user response:
You can get the call with summary(gm2)$call
I imagine something like this would work:
library(lme4)
head(iris)
lmm<-lmer(Petal.Length~Petal.Width (1|Species),data=iris)
lm<-lm(Petal.Length~Petal.Width Species,data=iris)
lm$call
summary(lmm)$call
getcall<-function(x){if(class(x)=="lmerMod"|class(x)=="glmerMod"){return(summary(x)$call)}else{return(x$call)}}
getcall(lm)
## lm(formula = Petal.Length ~ Petal.Width Species, data = iris)
getcall(lmm)
## glmer(formula = Petal.Length ~ Petal.Width (1 | Species), data = iris,
family = Gamma)
Now add your lapply
code:
models <- list(lm, lmm)
calls <- lapply(models, getcall)
calls
## [[1]]
## lm(formula = Petal.Length ~ Petal.Width Species, data = iris)
## [[2]]
## glmer(formula = Petal.Length ~ Petal.Width (1 | Species), data = iris,
family = Gamma)