如果未为此 S4 定义 $ 运算符,我如何从 glmerMod 对象中提取模型组件 class

How can I extract model components from glmerMod objects if $ operator not defined for this S4 class

我想提取模型调用以获取模型列表。该列表包括 glm 和 glmm。

这似乎适用于 glm 对象,但不适用于 glmerMod 对象

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

当我在 rstudio 环境窗格中单击 glmerMod 对象时,我可以看到该对象似乎确实具有与之关联的调用值。

有没有一种方法可以使用相同的函数从两种类型的模型中提取这些信息?这是我的偏好,因为我希望将其设置为 lapply 函数以应用于模型列表。

models <- list(gm1, gm2)

calls <- lapply(models, function(x) x$call)

您可以拨打 summary(gm2)$call

我想像这样的东西会起作用:

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)

现在添加您的 lapply 代码:

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)

你根本不需要 summary()

getCall(lmm)getCall(lm) 都有效。 (如果你深入研究这个,你会发现 getCall 的默认方法只是 getElement(., "call")getElement 是一个实用函数,它查找元素作为 either 一个列表元素 ($...) 或一个 S4 插槽 (@...).)