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")
})
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With