Load data file to R using tryCatch

What I'm trying to do is load a data file from a local directory. If it is not there, download it from the web server. I am currently using a nested tryCatch and it seems to work. Is this an attempt to complete this task in R?

tryCatch( 
  {  
    #attempt to read file from current directory
    # use assign so you can access the variable outside of the function
    assign("installations", read.csv('data.csv'), envir=.GlobalEnv) 
    print("Loaded installation data from local storage")
  },
  warning = function( w )
  {
     print()# dummy warning function to suppress the output of warnings
  },
  error = function( err ) 
  {
    print("Could not read data from current directory, attempting download...")
    #attempt to read from website
    tryCatch(
    {
        # use assign so you can access the variable outside of the function
        assign("installations", read.csv('http://somewhere/data.csv'), envir=.GlobalEnv) 
        print("Loaded installation data from website")
    },
    warning = function( w )
    {
      print()# dummy warning function to suppress the output of warnings
    },
    error = function( err )
    {
      print("Could not load training data from website!! Exiting Program")
    })
  })
+5
source share
1 answer

You can use the function file.exists(f)to find out if a file exists.

Other errors can occur, of course, such as permissions or problems with the file format, so you can still put everything in a try block.

+12
source

All Articles