r - 用于合并拟合模型的 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 个模型),而不必手动制作。
谢谢!!
解决方案
我想你正在寻找ls()
然后get
。假设您的工作区中已经有合适的模型,称为fits_mod1
,fits_mod2
等fits_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]
推荐阅读
- c# - 如何从 C#(GuitarPro 文件)中的 alphatab 分数生成 midi
- node.js - 如何在 express 应用中设置 webpack-hot-middleware?
- macos - vim 颜色与颜色方案不匹配(德古拉)
- angular - 超时后无法重新连接到套接字
- apache-kafka - 消费者在所有副本向领导者 kafka 确认之前接收消息
- reactjs - React 库中的自定义 Web 组件
- nestjs - 与 DTO 相比,嵌套 js 中的 DTO 接受更多参数
- reactjs - Autodesk Forge Viewer 和 React 组件
- android - 如何更改 apk 中的资源并重建应用程序
- javascript - 从 URL React 预加载图像