-4

I have a model object and I would like to apply it to predict values for number (e.g. 5) of new data stored as a list. All the data are of the same length and contain the same three predictor variables. In the end, I would like to have the predicted values stored as a matrix or list that has as many columns (or elements) as I have datasets used in prediction (e.g. 5).

Being a total newbie in R programming, I haven’t figured out any working solution to this problem.

putterinho
  • 11
  • 1
  • 2
  • 5
    This sounds like a standard `sapply` problem. But if you want specific help and coding suggestions, please take the time to create a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so we know how your objects are structured and named and so we know exactly what functions/packages are involved. – MrFlick Oct 11 '14 at 17:59

1 Answers1

2

this is simple example for your question: Firstly, let's generate some data and make a model object, in example, linear model:

training <- data.frame(y=rnorm(10), x1=rnorm(10), x2=rnorm(10))
model <- lm(y~., data=training)

Then, let's generating data in list for predictions:

testing <- list()
for (i in 1:5){
    testing[[i]] <- data.frame(x1=rnorm(10), x2=rnorm(10))
}

Finally, you apply prediction function with lapply for every new data in list and just unlist predictions' list to matrix:

predictions <- lapply(testing, function(x){predict(model, newdata=x)})
predictions_matrix <- matrix(unlist(predictions), nrow=5)
adomasb
  • 496
  • 4
  • 14
  • Thank you very much! This is exactly what I was looking for. I just couldn't formulate the lapply command correctly by myself. – putterinho Oct 11 '14 at 19:56
  • np, I hope this gonna help get familiar with apply functions. – adomasb Oct 11 '14 at 20:38
  • hi, if you could have a look at my question it would be great http://stackoverflow.com/questions/43427392/apply-predict-between-data-frames-within-two-lists thanks – aaaaa Apr 15 '17 at 15:04