I have a data frame containing a few models, and I want to apply the appropriate model to each line of a different data frame, and then add the model's predicted value in a new column of that data frame
I have a rather inelegant solution using a for-loop and requiring that I sort the data frame the models are applied to.
# sort my sample data (mtcars) by cylinder, so the final data lines up
mycars <- mtcars[order(mtcars$cyl),]
# build a linear model for each number of cylinders,
# estimating mpg from displacement
by_cyl <- group_by(mycars, cyl)
models <- by_cyl %>% do(mod = lm(mpg ~ disp, data = .))
# my inelegant solution for adding the predicted mpg into the dataset
prediction <- c()
for (i in models$cyl){
temp <- filter(mycars, cyl == i)
prediction <- c(prediction, predict((models %>% filter(cyl==i))$mod[[1]], temp))
}
mycars$mpg.pred <- prediction
I would like to be able to avoid using the for-loop, and if possible also leave the source date in its original order