【问题标题】:Load a data file in R using tryCatch使用 tryCatch 在 R 中加载数据文件
【发布时间】:2012-03-20 23:18:43
【问题描述】:

我想要做的是从本地目录加载一个数据文件。如果它不存在,则从网络服务器下载它。目前我正在使用嵌套的 tryCatch 并且它似乎可以工作。这是尝试在 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")
    })
  })

【问题讨论】:

    标签: r error-handling try-catch


    【解决方案1】:

    您可以使用函数file.exists(f) 来查看文件是否存在。

    当然,可能会出现其他错误,例如权限或文件格式问题,因此您可能希望将所有内容都包装在 try-block 中。

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 1970-01-01
      • 2014-09-08
      • 2015-06-01
      • 2018-10-02
      • 1970-01-01
      • 2017-06-10
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多