简体   繁体   English

在列表中存储模型(例如lm)会更改其类

[英]Storing model (e.g., lm) in list changes its class

I am storing lm models in a list and then want to use loops to access a specific model to extract results. 我将lm模型存储在列表中,然后想使用循环访问特定模型以提取结果。 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' terms.default(object)中的错误:没有条件组件或属性。另外:警告消息:在is.na(coef(mod))中:is.na()应用于类型为“ 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. 我检查了“ modl”类,并且它是“ list”类,因此我尝试更改该类,希望Anova能够访问lm对象中包含的所有相关信息,但无济于事。 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). 我知道整个对象实际上是通过检查名称并访问modl对象的不同级别(例如modl $ model)存储在列表中的。

Maybe lapply(lom, Anova,type="II") ? 也许是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.) (假设您的意思是lom [[x]] [y],而lolom是一个错字。)

Too many loops? 循环太多?

You want to run Anova on each model, that is, each entry of the list: 您要在每个模型(即列表的每个条目)上运行Anova:

for (x in 1:length(lom)) {
    modl <- lom[[x]]
    # etc
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM