Search code examples
routputgeocodeggmap

R: Identifying specific duplicate entries and geocoding with an output to new column


Here's what I am trying to do (I would like an opinion whether it is possible to do it or not)

I have 8000 entries with addresses (many of which are repeated because the data contains crime data)

I would like to use geocode say '800 Beatty st' which repeats 300 times, the longitude and latitude output into a new column.

I know how to geocode 1 specific location but don't know how to make it output into a new column. Additionally, given the size of the data I can't geocode 1 location at a time.

x <-c("800 BEATTY ST, VANCOUVER BC","800 BEATTY ST, VANCOUVER BC",
      "800 BEATTY ST, VANCOUVER BC","2900 PRINCE EDWARD ST, VANCOUVER BC",
      "2900 PRINCE EDWARD ST, VANCOUVER BC","2900 PRINCE EDWARD ST, VANCOUVER BC",
      "3600 KINGSWAY AVE, VANCOUVER BC")

require(ggmap)

geocode('800 BEATTY ST, VANCOUVER BC') Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=800+BEATTY+ST,+VANCOUVER+BC&sensor=false Google Maps API Terms of Service : http://developers.google.com/maps/terms lon lat 1 -123.1139 49.27763


Solution

  • I think you may be thinking a bit too hard here. If you have to repeat a same address multiple times, you can think how you wanna create a vector. For instance, you could do something like x <- rep(c("800 BEATTY ST, VANCOUVER BC", "2900 PRINCE EDWARD ST, VANCOUVER BC"), each = 5). If you run geocode(x) you see five entries for each address in the output.

    x <- rep(c("800 BEATTY ST, VANCOUVER BC", "2900 PRINCE EDWARD ST, VANCOUVER BC",
               "3600 KINGSWAY AVE, VANCOUVER BC"), times = c(3, 3, 1))
    
    library(ggmap)
    foo <- geocode(x)
    foo2 <- cbind(foo, x)
    
    #        lon      lat                                   x
    #1 -123.1139 49.27763         800 BEATTY ST, VANCOUVER BC
    #2 -123.1139 49.27763         800 BEATTY ST, VANCOUVER BC
    #3 -123.1139 49.27763         800 BEATTY ST, VANCOUVER BC
    #4 -123.0963 49.25880 2900 PRINCE EDWARD ST, VANCOUVER BC
    #5 -123.0963 49.25880 2900 PRINCE EDWARD ST, VANCOUVER BC
    #6 -123.0963 49.25880 2900 PRINCE EDWARD ST, VANCOUVER BC
    #7 -122.7899 49.26511     3600 KINGSWAY AVE, VANCOUVER BC