我想做的是从本地目录加载数据文件。如果不存在,则从网络服务器下载。目前我正在使用嵌套的 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")
})
})
您可以使用该功能file.exists(f)
查看文件是否存在。
当然,也可能会发生其他错误,例如权限或文件格式问题,因此您可能希望将所有内容都包装在 try 块中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)