尽管出现错误,但仍保持 R 代码运行?
使用之前 stackoverflow 中的代码函数:R:如何使用数据科学工具箱对简单地址进行地理编码
Using this code function from a previous stackoverflow:R: How to GeoCode a simple address using Data Science Toolbox
require("RDSTK")
library(httr)
library(rjson)
geo.dsk <- function(addr){ # single address geocode with data sciences toolkit
require(httr)
require(rjson)
url <- "http://www.datasciencetoolkit.org/maps/api/geocode/json"
response <- GET(url,query=list(sensor="FALSE",address=addr))
json <- fromJSON(content(response,type="text"))
loc <- json['results'][[1]][[1]]$geometry$location
return(c(address=addr,long=loc$lng, lat= loc$lat))
}
现在是示例代码.这工作正常:
Now Example Code. This works fine:
City<-c("Atlanta, USA", "Baltimore, USA", "Beijing, China")
r<- do.call(rbind,lapply(as.character(City),geo.dsk))
这不起作用.它说:json["results"][[1]][[1]] 中的错误:下标越界"
This does not work.It says: "Error in json["results"][[1]][[1]] : subscript out of bounds"
Citzy<-c("Leicester, United Kingdom")
do.call(rbind,lapply(as.character(Citzy),geo.dsk))
我认为错误是因为它找不到城市.所以我希望代码忽略它并继续运行.我该怎么做呢?任何帮助将不胜感激!
I believe the error is because it cannot find the city. So I would like the code to just ignore it and keep running. How would I go about doing this? Any help would be greatly appreciated!
最好使用 try/catch 块来处理错误.在 R 中,这看起来像这样(source):
Handling errors is best done with a try/catch block. In R, that would look something like this (source):
result = tryCatch({
# write your intended code here
Citzy<-c("Leicester, United Kingdom")
do.call(rbind,lapply(as.character(Citzy),geo.dsk))
}, warning = function(w) {
# log the warning or take other action here
}, error = function(e) {
# log the error or take other action here
}, finally = {
# this will execute no matter what else happened
})
因此,如果您遇到错误,它将进入错误块(并跳过尝试"部分中的其余代码)而不是停止您的程序.请注意,您应该始终对错误做某事",而不是完全忽略它;将消息记录到控制台和/或设置错误标志是一件好事.
So if you encounter the error, it will enter the error block (and skip the rest of the code in the "try" section) rather than stopping your program. Note that you should always "do something" with the error rather than ignoring it completely; logging a message to the console and/or setting an error flag are good things to do.