0

Creating an LOOCV loop using the randomForest package. I have adapted the following code from this link (https://stats.stackexchange.com/questions/459293/loocv-in-caret-package-randomforest-example-not-unique-results) however I am unable to reproduce a successful code.

Here is the code that I am running but on the iris dataset.

irisdata <- iris[1:150,]

predictionsiris <- 1:150

for (k in 1:150){
  set.seed(123)
  predictioniris[k] <- predict(randomForest(Petal.Width ~ Sepal.Length, data = irisdata[-k], ntree = 10), newdata = irisdata[k,,drop=F])[2]
}

What I would expect to happen is for it to run the random forest model on all but one row and then use that one row to test the model.

However, when I run this code, I get the following error:

Error in h(simpleError(msg, call)) : 
error in evaluating the argument 'object' in selecting a method for function 'predict': object 'Sepal.Length' not found

Any suggestions? I have been messing around with LOOCV code for the past two days including messing with code in this page (Compute Random Forest with a leave one ID out cross validation in R) and running the following:

iris %>%
mutate(ID = 1:516)

loocv <- NULL
for(i in iris$ID){
  test[[i]] <- slice(iris, i)
  train[[i]] <- slice(iris, i+1:516)
  rf <- randomForest(Sepal.Length ~., data = train, ntree = 10, importance = TRUE)
  loocv[[i]] <- predict(rf, newdata = test)
}

but I have had no success. Any help would be appreciated.

cmche
  • 1
  • 1

0 Answers0