簡體   English   中英

如何使用 Trycatch 跳過 R 中的數據下載錯誤

[英]How to use Trycatch to skip errors in data downloading in R

我正在嘗試使用dataRetrieval的 dataRetrieval package 從 USGS 網站下載數據。

為此,我在 R 中生成了一個名為getstreamflow的 function,例如,它在我運行時運行良好。

siteNumber <- c("094985005","09498501","09489500","09489499","09498502")
Streamflow = getstreamflow(siteNumber)

function的output是數據幀列表在此處輸入圖像描述

當下載數據沒有問題時,我可以運行 function,但對於某些站點,我收到以下錯誤:

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

為避免 function 在遇到錯誤時停止,我嘗試使用tryCatch ,如下代碼所示:

Streamflow = tryCatch(
  expr = {
    getstreamflow(siteNumber)
  }, 
  error = function(e) {
  message(paste(siteNumber," there was an error"))
})

遇到錯誤時,我希望 function 跳過該站,並希望 go 跳到下一個。 目前,我得到的 output 是下面顯示的,這顯然是錯誤的,因為它說對於所有站都存在錯誤:

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] “錯誤 1” “錯誤 2” “錯誤 3” “錯誤 4” “錯誤 5”

多個arguments

您表示您有要迭代的siteNumberdatatype

使用Map ,我們可以定義一個接受兩個輸入的 function :

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), error = function(e) message(paste(x, " there was an error")))
}

或者,按照建議,只需修改getstreamflow

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM