using predict with a list of lm() objects using predict with a list of lm() objects r r

using predict with a list of lm() objects


Here's my attempt:

predNaughty <- ddply(newData, "state", transform,  value=predict(modelList[[paste(piece$state[1])]], newdata=piece))head(predNaughty)#   year state    value# 1   50    50 5176.326# 2   51    50 5274.907# 3   52    50 5373.487# 4   53    50 5472.068# 5   54    50 5570.649# 6   55    50 5669.229predDiggsApproved <- ddply(newData, "state", function(x)  transform(x, value=predict(modelList[[paste(x$state[1])]], newdata=x)))head(predDiggsApproved)#   year state    value# 1   50    50 5176.326# 2   51    50 5274.907# 3   52    50 5373.487# 4   53    50 5472.068# 5   54    50 5570.649# 6   55    50 5669.229

JD Long edit

I was inspired enough to work out an adply() option:

pred3 <- adply(newData, 1,  function(x)    predict(modelList[[paste(x$state)]], newdata=x))head(pred3)#   year state        1# 1   50    50 5176.326# 2   51    50 5274.907# 3   52    50 5373.487# 4   53    50 5472.068# 5   54    50 5570.649# 6   55    50 5669.229


A solution with just base R. The format of the output is different, but all the values are right there.

models <- lapply(split(myData, myData$state), 'lm', formula = value ~ year)pred4  <- mapply('predict', models, split(newData, newData$state))


You need to use mdply to supply both the model and the data to each function call:

dataList <- dlply(newData, "state")preds <- mdply(cbind(mod = modelList, df = dataList), function(mod, df) {  mutate(df, pred = predict(mod, newdata = df))})