0

I'm new in R and I'm currently working with RandomForest Analysis. I need to create at least 100 replicates of a RF model, each one with different test/train data. I would like to automate the task wrapping the code into a loop if that's possible, and save the results of every model. Without a loop, I have to run the code every time and manually write the output.

This is my code:

#split data into 80 for training/20 for testing
obs_split <- obs_split %>%
split(if_else(runif(nrow(.)) <= 0.8, "train", "test"))
map_int(obs_split, nrow)

# grow random forest with ranger package
detection_freq <- mean(obs_split$train$species_observed)
# ranger requires a factor response to do classification
obs_split$train$species_observed <- factor(obs_split$train$species_observed)
rf <- ranger(formula =  species_observed ~ ., 
             data = obs_split$train,
             importance = "impurity",
             probability = TRUE,
             replace = TRUE, 
             sample.fraction = c(detection_freq, detection_freq))

I would appreciate any solution! Thank you

  • 1
    Please make this question *reproducible*. This includes sample code (you have code, but please include listing all relevant non-base R packages), sample *unambiguous* data (e.g., `dput(head(x))` or `data.frame(x=...,y=...)`), and expected output. Refs: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans Feb 26 '20 at 15:24
  • Simply put all your code in a user-defined `function` and iterate the function 100 times. Give it a try and let us know any issues. – Parfait Feb 26 '20 at 15:50

0 Answers0