What is the R equivalent for Excel IFERROR?

杀马特。学长 韩版系。学妹 提交于 2020-01-13 03:53:26

问题


I am trying to put IFERROR condition in R like Excel IFERROR Function. I am building a random forest model. To fine tune, i use tuneRF function. It helps to give optimal mtry parameter.

#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]

SOMETIMES, the above function returns error if OOB error would not improve in different iterations.

Error in if (Improve > improve) { : missing value where TRUE/FALSE needed.

Next Step : If the above function works fine, i use the value of best.m in the code below.

No ERROR in tuneRF function - Run the code below.

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

ERROR in tuneRF function - Run the code below.

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

Thanks in anticipation! Any help would be highly appreciated.


回答1:


You need to use try or tryCatch. This should work:

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)
}

However, the error given may represent a bug in the tuneRF function. Can you give a reproducible example, i.e. with a minimal dataset that will produce the error?



来源:https://stackoverflow.com/questions/31214361/what-is-the-r-equivalent-for-excel-iferror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!