I have an n x 1 list of addresses (whose class is 'character'), and I would like to output geocodes of each address in an n x 2 data.frame
(lat and long). How would you write this in R, and is there an efficient way to do this? It would be great if you could show some examples.
Right now, I'm just running a for loop like this:
library(taRifx.geo) ## for geocode
hmm <- c()
for (i in (R2012)){
hmm <- c(hmm, geocode(i, output = c("latlon", "latlona", "more", "all")))
}
But the result is an alternating single column of lat's and lon's:
$lon
[1] -122.1034
$lat
[1] 47.55304
$lon
[1] -122.1034
$lat
[1] 47.55304
If you force to use a for
loop, you could do something like this.
library(tidyr)
R2012 <- c("Tokyo", "Paris")
lonlat <- list()
for(i in R2012){
lonlat[[i]] <- geocode(i, output = c("latlon", "latlona", "more", "all"))
}
unnest(lonlat, city)
# city lon lat
#1 Tokyo 139.691706 35.68949
#2 Paris 2.352222 48.85661
But, I do not think a loop is necessary here. You may want to try something like this, instead.
foo <- geocode(R2012, output = c("latlon", "latlona", "more", "all"))
foo$city <- R2012
# lon lat city
#1 139.691706 35.68949 Tokyo
#2 2.352222 48.85661 Paris