I have 3 linear regression models built using the mtcars and would like to use those models to generate predictions for each rows of the mtcars tables. Those predictions should be added as additional columns (3 additional columns) of the mtcars dataframe and should be generated in a for loop using the leave one out approach. Furthermore predictions for model1 and model2 should be performed by "grouping" the cyl numbers whiles predictions made with the model 3 should be accomplished without doing any grouping.
So far I've been able to somewhat get something with a single model in the loop:
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