Apply list of models (randomForest) to list of data.frames to get list of factors

Hello together.

I created a list of 10 randomForest models with name "rf_models":

# list

# randomForest

And I created a list of 10 data.frames with name "dfs":

# list

# data.frame

I would like to predict

  • the 1st data.frame in dfs with the 1st randomForest model in rf_models,
  • the 2nd data.frame in dfs with the 2nd randomForest model in rf_models,
  • the 3rd data.frame in dfs with the 3rd randomForest model in rf_models,
    ... and so on...until ....
  • the 10th data.frame in dfs with the 10th randomForest model in rf_models.

The result should be a list containing 10 factors.

I would like to have this result in one code line:

prediction_1st   <-predict(rf_models[[1]],  dfs[[1]])
prediction_2nd   <-predict(rf_models[[2]],  dfs[[2]])
prediction_3rd   <-predict(rf_models[[3]],  dfs[[3]])
prediction_4th   <-predict(rf_models[[4]],  dfs[[4]])
prediction_5th   <-predict(rf_models[[5]],  dfs[[5]])
prediction_6th   <-predict(rf_models[[6]],  dfs[[6]])
prediction_7th   <-predict(rf_models[[7]],  dfs[[7]])
prediction_8th   <-predict(rf_models[[8]],  dfs[[8]])
prediction_9th   <-predict(rf_models[[9]],  dfs[[9]])
prediction_10th  <-predict(rf_models[[10]], dfs[[10]])

predictions_list <- list(prediction_1st, prediction_2nd, prediction_3rd, prediction_4th, prediction_5th, prediction_6th, prediction_7th, prediction_8th, prediction_9th, prediction_10th)

I tried several solutions with "lapply", but I could only manage to either apply one(!) model in rf_models (for example the first model) to all data.frames in dfs or apply all models to one(!) data.frame (for example the first data.frame) in dfs.

Is someone here who would like to help? :nerd_face:

I believe you should look at purrr:map2() as the ideal tool for such a task.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.