Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

warnings - Keep R code running despite Errors?

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))

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...