Excel IFERROR的R等效项是什么?

Ujj*_*ari 4 error-handling excel r try-catch

我正在尝试将R的IFERROR条件放在Excel的IFERROR函数之类的位置。我正在建立一个随机森林模型。为了进行微调,我使用了tuneRF功能。它有助于给出最佳的mtry参数。

#Selecting Optimal MTRY parameter
mtry <- tuneRF(dat3[, -36], dat3[,36], ntreeTry=1000, stepFactor=1.5,improve=0.01, trace=TRUE, plot=TRUE)
best.m <- mtry[mtry[, 2] == min(mtry[, 2]), 1]
Run Code Online (Sandbox Code Playgroud)

有时,如果OOB错误在不同的迭代中无法改善,则上述函数将返回错误。

if(改善>改善){时错误:缺少值,需要TRUE / FALSE。

下一步:如果上述功能正常,我在下面的代码中使用best.m的值。

tuneRF功能中没有错误-运行以下代码。

rf <-randomForest(classe~.,data=dat3, mtry=best.m, importance=TRUE,ntree=1000)
Run Code Online (Sandbox Code Playgroud)

tuneRF函数中的错误-运行以下代码。

#Train Random Forest
rf <-randomForest(classe~.,data=dat3, importance=TRUE,ntree=1000)
Run Code Online (Sandbox Code Playgroud)

谢谢您的期待!任何帮助将不胜感激。

Nic*_*edy 5

您需要使用trytryCatch。这应该工作:

mtry <- try(tuneRF(dat3[, -36], dat3[,36], ntreeTry=1000,
  stepFactor=1.5,improve=0.01, trace=TRUE, plot=TRUE))
if (!inherits(mtry, "try-error")) {
  best.m <- mtry[mtry[, 2] == min(mtry[, 2]), 1]
  rf <- randomForest(classe~.,data=dat3, mtry=best.m, importance=TRUE,ntree=1000)
} else {
  rf <- randomForest(classe~.,data=dat3, importance=TRUE,ntree=1000)
}
Run Code Online (Sandbox Code Playgroud)

但是,给出的错误可能表示该tuneRF功能存在错误。您能否举一个可重现的示例,即具有会产生错误的最小数据集?