【发布时间】:2021-10-19 23:47:39
【问题描述】:
我创建了一个包含 10 个名为“rf_models”的随机森林模型的列表:
class(rf_models)
# list
class(rf_models[[1]])
# randomForest
我创建了一个包含 10 个名为“dfs”的 data.frames 的列表:
class(dfs)
# list
class(dfs[[1]])
# data.frame
我想预测
- dfs 中的第一个 data.frame 与 rf_models 中的第一个 randomForest 模型,
- dfs 中的第二个 data.frame 与 rf_models 中的第二个 randomForest 模型,
- dfs 中的第三个 data.frame 与 rf_models 中的第三个 randomForest 模型, ... 以此类推...直到 ....
- dfs 中的第 10 个 data.frame 与 rf_models 中的第 10 个 randomForest 模型。
结果应该是一个包含 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 中的一个(!)模型(例如第一个模型)应用于 dfs 中的所有 data.frames 或将所有模型应用于一个(!) dfs中的data.frame(例如第一个data.frame)。
这里有人愿意帮忙吗? :D
【问题讨论】:
-
嗨,我想你需要
mapply。它有点像lapply,但你可以给它多个元素来“循环”。喜欢mapply(predict, rf_models, dfs)