Reputation: 10215
In using predict with a list of lm() objects, @JD Long asked for a solution to a problem which I encounter very often; typically, it comes up when models have been fit and plots are to be produced. JD Long's solution, edited in @Joshua Ulrich's answer was elegant, with the exception of the paste
that was required.
@hadley, chief of the ddply
empire, published a solution with mdply
which I found incomprehensible and far from elegant.
Now the dplyr
(and possibly tidyr
) is taking over: is there a more intuitive way to handle this common job?
For data and sample code, see JD Long's example cited above.
Upvotes: 2
Views: 202
Reputation: 81693
Using the data in the cited question, you can use the following approach with dplyr.
library(dplyr)
newData %>%
group_by(state) %>%
mutate(pred = predict(modelList[[as.character(state[1])]],
as.data.frame(year)))
However, I am not sure whether this solution is more elegant than the existing ones.
Upvotes: 1