I am trying to add a column of predictions to a dataframe that has a list column that contains an lm model. I adopted some of the code from this post.
I have made a
You could take advantage of the newdata
argument to predict
.
I use map2_dbl
so it returns just the single value rather than a list.
mutate(Pred = map2_dbl(model, 1:5, ~predict(.x, newdata = data.frame(ind = .y))))
# A tibble: 5 x 4
groups the_data model Pred
1 A -0.4822045
2 B -0.1357712
3 C -0.2455760
4 D 0.4818425
5 E -0.3473236
If you add ind
to the dataset before prediction you can use that column instead of 1:5
.
mutate(ind = 1:5) %>%
mutate(Pred = map2_dbl(model, ind, ~predict(.x, newdata = data.frame(ind = .y) )))
# A tibble: 5 x 5
groups the_data model ind Pred
1 A 1 -0.4822045
2 B 2 -0.1357712
3 C 3 -0.2455760
4 D 4 0.4818425
5 E 5 -0.3473236