I am working in a modeling problem where I have to estimate multiple models per group using specific variables. After having all models per groups I need to compute the estimated values (fitted values) and standard errors (se) for all of them. I found we can use broom
and dplyr
for this. So, I sketched next code using iris
data:
library(dplyr)
library(broom)
#Data
data("iris")
#Code
iris2 <- iris %>% group_by(Species)
Data iris2
has a group based on Species
. With this I compute the different models using next code:
#Models
models <- iris2 %>%
do(
model1 = lm(Sepal.Length~Sepal.Width, data = .),
model2 = lm(Sepal.Width~Petal.Width, data = .),
model3 = lm(Petal.Width~Sepal.Length+Sepal.Width, data = .),
model4 = lm(Petal.Width~Petal.Length+Sepal.Length, data = .))
Which produces:
models
# A tibble: 3 x 5
# Rowwise:
Species model1 model2 model3 model4
<fct> <list> <list> <list> <list>
1 setosa <lm> <lm> <lm> <lm>
2 versicolor <lm> <lm> <lm> <lm>
3 virginica <lm> <lm> <lm> <lm>
All is fine. Now, I need to compute the predictions for the entire dataset iris2
using the four models. I used a merge approach to add the models to the iris2
dataframe:
#Merge with original data
Merged <- iris2 %>%
left_join(models)
At this point, the data has all the models but I am not sure of how to proceed to compute the fitted values and standard error. In the end I would like to have two additional columns per each model like predict.mod1
and se.mod1
until predict.mod4
and se.mod4
for all the observations in iris2
.
This is my main issue as I do not know how to use predict()
to take each model1
, model2
, model3
and model4
to compute both fitted and se values. I know I can use predict()
and predict(model,data,se=T)$$se.fit
to obtain the values in an isolated dataframe with one model but in this case I have multiple models after the merge action.
I have checked some posts around the site and they use mutate(result = map2(fit, data, predict))
to create the estimations. I tried a similar approach but did not work.
Many thanks for your help.