Search code examples
rgeocodingggmap

How can I extract the zip code from the ggmap output?


structure(list(trip_count = 1:10, pickup_longitude = c(-73.964096, 
-73.989037, -73.934998, -73.93409, -73.998222, -74.004478, -73.994881, 
-73.955917, -73.993607, -73.948265), pickup_latitude = c(40.764141, 
40.760208, 40.746693, 40.715908, 40.750809, 40.741501, 40.74033, 
40.776054, 40.758625, 40.778515)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

So I am trying to recode the longitude and latitude data into ZIP codes of NYC. With revgeocodingfrom ggmap I already get some results:

res <- revgeocode(c(test$pickup_longitude[1],test$pickup_latitude[1]), output = "all")

However,

  1. I can apply this procedure just to one location data at a time. Is there a way I can get the results for every location at once like
res <- revgeocode(c(test$pickup_longitude,test$pickup_latitude), output = "all")
  1. How can I extract the ZIP Code from the ggmap results so that I can create a new column in the data frame with the correspondent zip code? Somehow the zip code is stored in a very strange way (see picture). How can I access this information in the console?enter image description here

The solutions does not have to work in ggmap, maybe there is a different approach to get the ZIP codes from the longitude and latitude data? Thanks!


Solution

  • I don't have an API key, but try something like the following:

    my_func <- function(longlat, output){
      list(list(list(c(vector("list", 7), list(12345L)))))
    }
    
    test %>% 
      rowwise() %>% 
      mutate(zip = list(my_func(c(pickup_longitude, pickup_latitude), output = "all"))) %>% 
      mutate(zip = zip[[1]][[1]],
             zip = zip[[8]])
    

    Replace my_func with revgeocode . You'll have to figure out exactly how to pick out the zip code from the output. But you can try something like the above.