我試圖用R中的while循環實現tryCatch,但一直在遇到問題。我試圖實現一些建議的解決方案(圍繞循環),但沒有成功。在R中使用tryCatch與while循環
本質上來說,我是用R來查詢一個API,並通過一些相關的參數(精確的經度和緯度)進行循環。我需要tryCatch塊的原因是,有時URL請求會失敗,從而導致腳本停止運行。我想要做的就是忽略錯誤,將循環計數器增加1並繼續提取。
while循環我已成立是(FYI - 長度是指繞環數據幀的長度上):
i <- 1
while(i <= length) {
x_cord <- geocode_area$X[i]
y_cord <- geocode_area$Y[i]
target <- getUrl(x_cord,y_cord)
dat <- fromJSON(target)
geocode_area$Block[i] <- dat$result$geographies$`2010 Census Blocks`[[1]]$BLOCK
print(paste(i/length*100,"% completed",sep=""))
print(dat$result$geographies$`2010 Census Blocks`[[1]]$BLOCK)
i <- i + 1
}
使用getURL()函數定義爲:
getUrl <- function(x,y) {
root <- "http://geocoding.geo.census.gov/geocoder/geographies/coordinates?"
u <- paste0(root,"x=", x,"&y=", y,"&benchmark=4&vintage=4&format=json")
return(URLencode(u))
}
的輸入data.frame到while循環看起來是這樣的(注意我已經拋出字符串來模擬錯誤來測試tryCatch正在工作):
X Y Block
1 -122.425891675136 37.7745985956747 0
2 -122.42436302145 37.8004143219856 0
3 -122.426995326766 37.8008726327692 0
4 -122.438737622757 37.7715411720578 0
5 abc zsads 0
我已經嘗試了一些SO和其他解決方案,但結果似乎沒有正常工作。誰能幫忙?
謝謝!
插孔
如果您在數據框中包含一些示例參數,它可能會有幫助。 – TARehman
嗨。這是一個非常簡單的數據框架(如果我正確理解你的話)。我已經用輸入df的頭部更新了這個問題。謝謝! –
爲什麼你使用'while'?看起來像'for(i in 1:length)tryCatch({...})'正在做工作。 – Marek