大佬教程收集整理的这篇文章主要介绍了如何使用 Trycatch 跳过 R 中数据下载中的错误,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用 R 的 dataRetrIEval
包从 USGS 网站下载数据。
为此,我在 R 中生成了一个名为 getstreamflow
的函数,例如,当我运行时它可以正常工作。
sitenumber <- c("094985005","09498501","09489500","09489499","09498502")
Streamflow = getstreamflow(sitenumber)
函数的输出是一个数据框列表
我可以在下载数据没有问题的情况下运行该功能,但对于某些站点,我收到以下错误:
request Failed [404]. retrying in 1.1 seconds...
request Failed [404]. retrying in 3.3 seconds...
For: https://waterserviceS.Usgs.gov/nwis/site/?siteOutput=Expanded&format=rdb&site=0946666666
为避免函数在遇到错误时停止,我尝试使用 tryCatch
,如下代码所示:
Streamflow = tryCatch(
expr = {
getstreamflow(sitenumber)
},error = function(E) {
message(paste(sitenumber," there was an error"))
})
我希望函数在遇到错误时跳过该站并转到下一个。目前,我得到的输出是下面显示的输出,这显然是错误的,因为它说所有站都存在错误:
094985005 there was an error09498501 there was an error09489500 there was an error09489499 there was an error09498502 there was an error09511300 there was an error09498400 there was an error09498500 there was an error09489700 there was an error09500500 there was an error09489082 there was an error09510200 there was an error09489100 there was an error09490500 there was an error09510180 there was an error09494000 there was an error09490000 there was an error09489086 there was an error09489089 there was an error09489200 there was an error09489078 there was an error09510170 there was an error09493500 there was an error09493000 there was an error09498503 there was an error09497500 there was an error09510000 there was an error09509502 there was an error09509500 there was an error09492400 there was an error09492500 there was an error09497980 there was an error09497850 there was an error09492000 there was an error09497800 there was an error09510150 there was an error09499500 there was an error... <truncated>
我在使用 tryCatch
时做错了什么?
回答
您在 tryCatch
之外编写了 getstreamflow
。因此,如果一个站点失败,那么 getstreamflow
将返回一个错误而不是其他任何内容。您应该一次提供 1 个站点,或者将 tryCatch
放在 getstreamflow
中。
示例
x <- 1:5
fun <- function(X) {
for (i in X) if (i == 5) stop("ERROR")
return(x^2)
}
tryCatch(fun(X),error = function(E) paste0("wrong",X))
返回:
[1] "wrong1" "wrong2" "wrong3" "wrong4" "wrong5"
多个参数
您表示您有 sitenumber
和 datatype
可以迭代。
使用 @H_908_3@map,我们可以定义一个接受两个输入的函数:
@H_908_3@map(function(x,y) tryCatch(fun(x,y),error = function(E) message(paste(x," there was an error"))),x = sitenumber,y = datatypE)
使用 for 循环,我们可以遍历它们:
Streamflow <- vector(mode = "list",length = length(sitenumber))
for (i in seq_along(sitenumber)) {
Streamflow[[i]] <- tryCatch(getstreamflow(sitenumber[i],datatypE)," there was an error")))
}
或者,按照建议,只需修改 getstreamflow
。
以上是大佬教程为你收集整理的如何使用 Trycatch 跳过 R 中数据下载中的错误全部内容,希望文章能够帮你解决如何使用 Trycatch 跳过 R 中数据下载中的错误所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。