在R中创建for循环以运行相同的模型10次

时间:2017-11-29 18:42:02

标签: r for-loop

我试图在插补后在R中写一个循环。估算估算了10个数据集,我希望在每个数据集中运行相同的模型,并预测每个数据集中的结果得分。我当前的代码不起作用:

for (i in 1:10) {
impi <- glm(died ~ agecat + female_1 + insurance + mech + transfer +
            iss + mxaisbr1 + maxais + cm_chf_1 + cm_mets_1 + cm_liver_1 +
            cm_htn_c_1 + cm_bldloss_1 + state, data = subset(imp, .imp == i), family = binomial)
preimpi <- predict(impi, type = c('response'))
}

没有循环,我必须输入相同的代码10次

imp1 <- glm(died ~ agecat + female_1 + insurance + mech + transfer +
            iss + mxaisbr1 + maxais + cm_chf_1 + cm_mets_1 + cm_liver_1 +
            cm_htn_c_1 + cm_bldloss_1 + state, data = subset(imp, .imp == 1), family = binomial)
preimp1 <- prediect(imp1, type = c('response'))
imp2 <- glm(died ~ agecat + female_1 + insurance + mech + transfer +
            iss + mxaisbr1 + maxais + cm_chf_1 + cm_mets_1 + cm_liver_1 +
            cm_htn_c_1 + cm_bldloss_1 + state, data = subset(imp, .imp == 2), family = binomial)
preimp2 <- prediect(imp2, type = c('response'))
etc...

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:3)

一种解决方案是将impi和preimpi初始化为列表,例如

impi = list()
preimpi = list()
for (i in 1:10) {
  impi[[i]] <- glm(died ~ agecat + female_1 + insurance + mech +
               transfer + iss + mxaisbr1 + maxais + cm_chf_1 + 
               cm_mets_1 + cm_liver_1 + cm_htn_c_1 + cm_bldloss_1 +
               state, data = subset(imp, .imp == i), family = binomial)
  preimpi[[i]] <- predict(impi[[i]], type = c('response'))
}

请注意使用双括号来索引列表。

编辑:这是一个使用lapply作为预测线的替代方案,它应该产生与上面例子相同的输出。

impi = list()
for (i in 1:10) {
  impi[[i]] <- glm(died ~ agecat + female_1 + insurance + mech +
               transfer + iss + mxaisbr1 + maxais + cm_chf_1 + 
               cm_mets_1 + cm_liver_1 + cm_htn_c_1 + cm_bldloss_1 +
               state, data = subset(imp, .imp == i), family = binomial)
}
preimpi = lapply(impi, FUN = predict, type = "response")