0

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 (e.g., modl$model).

0

2 Answers 2

3

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]))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Although it's hard for me to follow the double embedded lapply, this response has opened things up for me. Specifically, I finally am getting how lapply should be used instead of loops and the level of dynamic coding possible for me has increased by an order of magnitude.
Sorry if I missed anything, but this doesn't really address the question on why the mode of the objects where changed when calling list()?
1

(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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.