使用tryCatch将数据加载到R中 [英] Load a data file in R using tryCatch

查看:67
本文介绍了使用tryCatch将数据加载到R中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要尝试的是从本地目录加载数据文件。如果不存在,请从网络服务器下载。目前,我正在使用嵌套的tryCatch,它似乎可以正常工作。这是尝试在R中完成该任务的正确方法吗?

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


推荐答案

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

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

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

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.

这篇关于使用tryCatch将数据加载到R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆