I want to fit a model using data from each group in a dataframe. Then I want to use this model to predict it to all data in the dataframe that was not in the group and compute a metric like the RMSE. I have some issues to wrap my head around how I could achieve something like this without doing many manual steps. I have the following toy-example using the mtcars
data.
I want to fit the model lm(mpg ~ wt, data=mtcars)
for each group of cyl
and use this model and the data from the remaining points to copmute a value like the RMSE.
I wrote the following code, but it is not working and also does not feel so good. I'd be happy to hear about any tipps and tricks:)
library(tidyverse)
# 'global' model
lm(mpg ~ wt, data=mtcars)
# 1. fit one model for each class of cyl,
# 2. use it to predict the remaining ones,
# 3. get the RMSE for each class of cyl
res = mtcars %>%
group_by(cyl) %>%
mutate(
models = list(lm(mpg ~ wt, data = cur_data())), # why does this needs to be a list?
ref_data = list(mtcars %>% filter(!cyl %in% cur_data()$cyl[[1]])), # get all the data minus the current group at put it in a list column
predict = map(models, ~predict(.x, newdata=mtcars %>% filter(!cyl %in% cur_data()$cyl[[1]]))), # predict it on all others -> will store one df per row...
rmse = map2_dbl(predict, ref_data, ~sqrt((sum(.y - .y)^2))/length(predict))
)