使用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.