I am storing lm models in a list and then want to use loops to access a specific model to extract results. Specifically, I have code like this:
model1 <- lm(dv ~ group,data=df,na.action=na.omit)
model2 <- lm(dv ~ cov + group,data=df,na.action=na.omit)
model3 <- lm(dv ~ group,data=df_out,na.action=na.omit)
model4 <- lm(dv ~ cov + group,data=df_out,na.action=na.omit)
lom <- list(main=model1,main_cov=model2,main_out=model3, main_cov_out=model4)
for (x in c(1:length(lom))) {
for (y in c(1:length(lom[[x]]))) {
modl <- lolom[[x]][y]
class(modl) <- "lm"
anov <- Anova(modl,type="II") # (from Car package)
} # (y in c(1:length(lom[[x]])))
} # (x in c(1:length(lom)))
but get this error...
Error in terms.default(object) : no terms component nor attribute In addition: Warning message: In is.na(coef(mod)) : is.na() applied to non-(list or vector) of type 'NULL'
I checked the class of "modl" and it was "list" so I tried to change the class hoping that Anova would then be able to access all the relevant information contained in the lm object, but to no avail. I know the whole object is actually stored in the list by checking names and accessing different levels of the modl object (eg, modl$model).
Maybe lapply(lom, Anova,type="II")
?
and if you want a list of all the objects:
lapply(lom, function(x) lapply(seq_along(names(x)), function(i) x[i]))
(Assuming that you really mean lom[[x]][y] and lolom is a typo.)
Too many loops?
You want to run Anova on each model, that is, each entry of the list:
for (x in 1:length(lom)) {
modl <- lom[[x]]
# etc
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.