将模型列表 (randomForest) 应用于 data.frames 列表以获取因子列表

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

我创建了一个包含 10 个随机森林模型的列表,名称为“rf_models”:

class(rf_models)
# list

class(rf_models[[1]])
# randomForest

我创建了一个包含 10 个 data.frames 的列表,名称为“dfs”:

class(dfs)
# list

class(dfs[[1]])
# data.frame

我要预测

结果应该是一个包含 10 个因素的列表。

我想在一个代码行中得到这个结果:

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)

我用“lapply”尝试了几种解决方案,但我只能设法将 rf_models 中的一个(!)模型(例如第一个模型)应用于所有 data.frames 在 dfs 中或将所有模型应用于 dfs 中的一个(!)data.frame(例如第一个 data.frame)。

这里有人愿意帮忙吗? :D

使用 Map 这将帮助您同时迭代 rf_modelsdfs

prediction <- Map(predict, rf_models, dfs)

等效的 purrr 函数是 map2

prediction <- purrr::map2(rf_models, dfs, predict)