Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a data file in R using tryCatch

What I am trying to do is load a data file from the local directory. If it is not there then download it from a webserver. Currently I am using a nested tryCatch and it appears to work. Is this the correct way to 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")
    })
  })
like image 645
Greg Avatar asked Mar 02 '12 12:03

Greg


1 Answers

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

Other errors may occur, of course, such as permissions or file format problems, so you might want to wrap everything in a try-block anyway.

like image 50
Spacedman Avatar answered Sep 18 '22 16:09

Spacedman