【发布时间】:2021-03-02 10:50:49
【问题描述】:
我有 3 个使用 mtcars 构建的线性回归模型,并希望使用这些模型为 mtcars 表的每一行生成预测。这些预测应作为 mtcars 数据帧的附加列(3 个附加列)添加,并应使用留一法在 for 循环中生成。 此外,模型 1 和模型 2 的预测应通过“分组”cyl 数来执行 而使用模型 3 所做的预测应该在不进行任何分组的情况下完成。
到目前为止,我已经能够在循环中使用单个模型获得一些东西:
model1 =lm(hp ~ mpg, data = mtcars)
model2 =lm(hp ~ mpg + hp, data = mtcars)
model3 =lm(hp ~ mpg + hp + wt, data = mtcars)
fitted_value <- NULL
for(i in 1:nrow(mtcars)){
validation<-mtcars[i,]
training<-mtcars[-i,]
model1<-lm(mpg ~ hp, data = training)
fitted_value[i] <-predict(model1, newdata = validation)
}```
I would like to be able to generate all the model predictions by first putting all the models in a list or vector and attaching the result to the mtcars dataframe. Somthing lke thislike this:
```model1 =lm(hp ~ mpg, data = mtcars)
model2 =lm(hp ~ mpg + hp, data = mtcars)
model3 =lm(hp ~ mpg + hp + wt, data = mtcars)
models <- list(model1, model2, model3)
fitted_value <- NULL
for(i in 1:nrow(mtcars)){
validation<-mtcars[i,]
training<-mtcars[-i,]
fitted_value[i] <-predict(models, newdata = validation)
}```
Thank you for you help
【问题讨论】:
标签: r for-loop model regression