how to handle error from geocode (ggmap R)

1.6k views Asked by At

I'm using ggmap to find locations. Some locations generates error. For example,

library(ggmap)

loc = 'Blue Grass Airport'
geocode(loc, output = c("more"))

results in

Error in data.frame(long_name = "Blue Grass Airport", short_name = "Blue Grass Airport",  : 
  arguments imply differing number of rows: 1, 0

It's ok if I can't get results for some locations, but I'm trying to work on 100 locations in a list. So is there a way to get NA instead of error and keep things go on? E.g.,

library(ggmap)

loc = c('Blue Grass Airport', 'Boston MA', 'NYC')
geocode(loc, output = c("more"))

should generate

NA
Result for Boston
Result for New York City
1

There are 1 answers

3
Tim Biegeleisen On BEST ANSWER

You can make use of the R tryCatch() function to handle these errors gracefully:

loc = 'Blue Grass Airport'
x <- tryCatch(geocode(loc, output = c("more")),
              warning = function(w) {
                            print("warning"); 
                            # handle warning here
                        },
              error = function(e) {
                          print("error");
                          # handle error here
                      })

If you intend to loop over locations explicitly using a for loop or using an apply function, then tryCatch() should also come in handy.