我是R的初学者,所以我想寻求一些帮助。
我正在尝试使用for循环来迭代我估算的拟合模型,以便在合并模型并随后计算模型的R平方时增加一些效率。
# 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个型号),而不是必须手动制作它们。
谢谢!!
发布于 2020-03-31 23:54:17
一种更像R的方法是这样做的。将不同的公式存储在列表中,然后在列表上使用lapply来拟合和总结您的模型。
models <- list(
Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
+ Tr_Initial + Tr_Nationality,
Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
+ Tr_Initial + Tr_Nationality
+ Racism_neighborhood + Homosexuality,
Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
+ Tr_Initial + Tr_Nationality
+ Confidence_police + Interfere_police,
Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
+ Tr_Initial + Tr_Nationality
+ Satisfaction + Feeling_happy,
Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
+ Tr_Initial + Tr_Nationality
+ Violence + Avoid_danger,
Trust ~ Tr_Family + Tr_Neighborhood + Tr_Personally
+ Tr_Initial + Tr_Nationality
+ Adv_Taken + Control_life
+ Wealth_accumulation)
fits <- lapply(models, lm.mids, data=miceOut3)
pools <- lapply(fits, pool)
poolR2 <- lapply(fits, pool.r.squared)您是否可以通过fits[[1]]、fits[[2]]等获得个人合身
https://stackoverflow.com/questions/60953660
复制相似问题