首页 > 解决方案 > 用于合并拟合模型的 for 循环

问题描述

我是 R 的初学者,所以想寻求一些帮助。

我正在尝试使用 for 循环遍历我的估算拟合模型,以便在池化模型和随后计算模型的 Rsquared 时增加一些效率。

# Model with all Trust variables

fits_mod1 <- lm.mids(Trust ~  Tr_Family + Tr_Neighborhood + Tr_Personally
                     + Tr_Initial + Tr_Nationality, data = miceOut3)

# Model with all Trust + Discriminatory attitudes variables

fits_mod2 <- lm.mids(Trust ~  Tr_Family + Tr_Neighborhood + Tr_Personally
                     + Tr_Initial + Tr_Nationality
                     + Racism_neighborhood + Homosexuality, data = miceOut3)

# Model with all Trust + Police variables

fits_mod3 <- lm.mids(Trust ~  Tr_Family + Tr_Neighborhood + Tr_Personally
                     + Tr_Initial + Tr_Nationality 
                     + Confidence_police + Interfere_police, data = miceOut3)

# Model with all Trust + Happiness variables

fits_mod4 <- lm.mids(Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
                     + Tr_Initial + Tr_Nationality
                     + Satisfaction + Feeling_happy, data = miceOut3)

# Model with all Trust + Danger variables

fits_mod5 <- lm.mids(Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
                     + Tr_Initial + Tr_Nationality
                     + Violence + Avoid_danger, data = miceOut3)

# Model with all Trust + Control and Advantage variables

fits_mod6 <- lm.mids(Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
                     + Tr_Initial + Tr_Nationality
                     + Adv_Taken + Control_life 
                     + Wealth_accumulation, data = miceOut3)

## Pool the fitted models:
poolFit1 <- pool(fits_mod1)
poolFit2 <- pool(fits_mod2)
poolFit3 <- pool(fits_mod3)
poolFit4 <- pool(fits_mod4)
poolFit5 <- pool(fits_mod5)
poolFit6 <- pool(fits_mod6)

## Compute the pooled R^2:
pool.r.squared(fits_mod1)
pool.r.squared(fits_mod2)
pool.r.squared(fits_mod3)
pool.r.squared(fits_mod4)
pool.r.squared(fits_mod5)
pool.r.squared(fits_mod6)

# select the model with highest rsquared 
pool.r.squared(fits_mod2)[1] - pool.r.squared(fits_mod1)[1]

我的意图是让每个“fits_model”的“poolFit”在 1:6 的范围内(对于 6 个模型),而不必手动制作。

谢谢!!

标签: rfor-loop

解决方案


我想你正在寻找ls()然后get。假设您的工作区中已经有合适的模型,称为fits_mod1,fits_mod2fits_mod3

fits_mods <- ls(pattern="^fits_mod\\d+")
fits_mods
# [1] "fits_mod1" "fits_mod2" "fits_mod3"

get(fits_mod[1]) # This shows the results.

poolFits <- list()
for(i in 1:3) {
  poolFits[[i]] <- pool(get(fits_mod[i]))
}

poolFits # show them all

# select the model with highest r-squared 
pool.r.squared(get(fits_mods[2]))[1] - pool.r.squared(get(fits_mods[1]))[1]

推荐阅读