0

My R code is trying to open a RDS file in a for loop as follows:

for(i in 1:run_loops){
    source("./scripts/load_data.R")
    model <- readRDS(file=paste(model_directory,"/",modelname,".Rds", sep="")) #STOPS-HERE!!!
    source("./scripts/prediction.R")
  }

R stops when there is no model file.
How do I get it to move to the next iteration instead of stopping?

P.S. modelname variable changes each time load_data.R is sourced.

uguros
  • 356
  • 2
  • 6
  • 19

2 Answers2

2

This should do the trick:

for(i in 1:run_loops) {
  tryCatch(
    expr = {
      source("./scripts/load_data.R")
      model <-
        readRDS(file = paste(model_directory, "/", modelname, ".Rds", sep = "")) #STOPS-HERE!!!
      source("./scripts/prediction.R")
    },
    error = function(e) {
      print(paste0(i, ' not done'))
    }
  )
}
Steffen
  • 206
  • 1
  • 7
1

You can use file.exists

file_name <- paste0(model_directory,"/",modelname,".Rds")
if(file.exists(file_name)) {
  #do something
} else {
  #do something else
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213