Load a data file in R using tryCatch

*爱你&永不变心* 提交于 2019-12-22 05:14:31

问题


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")
    })
  })

回答1:


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.



来源:https://stackoverflow.com/questions/9533552/load-a-data-file-in-r-using-trycatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!