2

I'm pretty sure that there's a straightforward answer to this, but with my limited R experience I'm having trouble coming up with it. I have a list of data frames representing different experiments, and for each of these data frames I have generated a regression model - the models are contained in a separate list. What I would like to do use the predict() function to predict responses for every possible combination of data frame and model. Here's an example using just two data frames and two models to illustrate the desired outcome:

predictor <- runif(1000)
response <- runif(1000)
data.1 <- data.frame(predictor,response) # generate first data frame

predictor <- runif(1000)
response <- runif(1000)
data.2 <- data.frame(predictor,response) # generate second data frame

model.1 <- lm(response ~ predictor,data=data.1) # generate model for data.1
model.2 <- lm(response ~ predictor,data=data.2) # generate model for data.2

pred.1.1 <- predict(model.1,newdata=data.1) # use model.1 to predict outcome based on data.1
pred.1.2 <- predict(model.1,newdata=data.2) # use model.1 to predict outcome based on data.2
pred.2.1 <- predict(model.2,newdata=data.1) # use model.2 to predict outcome based on data.1
pred.2.2 <- predict(model.2,newdata=data.2) # use model.2 to predict outcome based on data.2

This is simple enough for the two-case example above, but in fact I have 10 different data frames and 10 models so the above approach would be both tedious and dumb. I've tried various approaches to this using lapply() but I can't seem to get the syntax right -any pointers on how best to perform a function on all possible pairwise combinations of the elements of two lists?

Thanks, Seth

1 Answers1

4

Life is made easier if you put your models and data frames into lists.

modlst <- list(model.1, model.2, ....)
datlst <- list(data.1, data.2, ....)

out <- lapply(modlst, function(mod) {
           lapply(datlst, function(dat) predict(mod, dat))
       })
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187