2

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.

Community
  • 1
  • 1
Dieter Menne
  • 10,076
  • 44
  • 67
  • 1
    did you consider `nlme::lmList`? It uses a grouping variable in the formula, which in my opinion is a very intuitive interface. – baptiste Jul 23 '14 at 09:48
  • +1 @baptiste. For those who are interested, [here is a nice demo](http://stackoverflow.com/a/24907275/980833) of how simple `lmList()` and `predict.lmList()` make this job. – Josh O'Brien Jul 23 '14 at 13:09
  • Yes, I am a heavy nlme user, predict.lmList is the sample app in background. But in Joshua's question, lm only served as an example, and a generalization to other fits, e.g. from stan/mcmc is what I am looking for. – Dieter Menne Jul 23 '14 at 13:21
  • 1
    I don't think it's possible to do this elegantly with dplyr at the moment. The way I imagine it would work is that you'd use some tidyr verb to get a data frame where one column is a column of data frames (the data forming the prediction grid), you'd then join that with the data frame containing the models, then `do(predict(.$model, .$data))`. – hadley Jul 23 '14 at 19:38

1 Answers1

1

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.

Community
  • 1
  • 1
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • That will serve as an accepted answer, if there is no better one. In my eye, the two casts are an indication that the solution is not really elegant; as.character(state[1]) (or paste in the original version) has a bit of a code smell. – Dieter Menne Jul 23 '14 at 13:24