gpt4 book ai didi

r - 使用 tryCatch 在 R 中加载数据文件

转载 作者:行者123 更新时间:2023-12-04 10:20:16 25 4
gpt4 key购买 nike

我想要做的是从本地目录加载数据文件。如果它不存在,则从网络服务器下载它。目前我正在使用嵌套的 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-block 中。

关于r - 使用 tryCatch 在 R 中加载数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9533552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com