【发布时间】:2021-10-12 11:17:38
【问题描述】:
我有一个包含 9 个输入变量和 1 个输出变量的 R 数据框。我想使用每个单独的输入找到 randomForest 的准确性,并将它们添加到列表中。为此,我需要遍历一个公式列表,如下面的代码所示:
library(randomForest)
library(caret)
formulas = c(target ~ age, target ~ sex, target ~ cp,
target ~ trestbps, target ~ chol, target ~ fbs,
target ~ restecg, target ~ ca, target ~ thal)
test_idx = sample(dim(df)[1], 60)
test_data = df[test_idx, ]
train_data = df[-test_idx, ]
accuracies = rep(NA, 9)
for (i in 1:length(formulas)){
rf_model = randomForest(formulas[i], data=train_data)
prediction = predict(rf_model, newdata=test_data, type="response")
acc = confusionMatrix(test_data$target, prediction)$overall[1]
accuracies[i] = acc
}
我遇到了一个错误,
if (n==0) stop("data (x) has 0 rows") 中的错误:参数是 长度为零的调用:... eval -> eval -> randomForest -> randomForest.default 执行停止
错误与传递给randomForest的formulas[i]参数有关,当我输入公式名称作为参数时(例如rf_model = randomForest(target ~ age, data=train_data),没有错误。
还有其他方法可以遍历 randomForest 吗?
谢谢!
【问题讨论】:
标签: r random-forest