Skip to content

Instantly share code, notes, and snippets.

@aleszu
Created April 21, 2017 18:33
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save aleszu/04a486ec0c3f61a8e7ce8f9b37d9e986 to your computer and use it in GitHub Desktop.
Save aleszu/04a486ec0c3f61a8e7ce8f9b37d9e986 to your computer and use it in GitHub Desktop.
# Geocoding a csv column of "addresses" in R
#load ggmap
library(ggmap)
# Select the file from the file chooser
fileToLoad <- file.choose(new = TRUE)
# Read in the CSV data and store it in a variable
origAddress <- read.csv(fileToLoad, stringsAsFactors = FALSE)
# Initialize the data frame
geocoded <- data.frame(stringsAsFactors = FALSE)
# Loop through the addresses to get the latitude and longitude of each address and add it to the
# origAddress data frame in new columns lat and lon
for(i in 1:nrow(origAddress))
{
# Print("Working...")
result <- geocode(origAddress$addresses[i], output = "latlona", source = "google")
origAddress$lon[i] <- as.numeric(result[1])
origAddress$lat[i] <- as.numeric(result[2])
origAddress$geoAddress[i] <- as.character(result[3])
}
# Write a CSV file containing origAddress to the working directory
write.csv(origAddress, "geocoded.csv", row.names=FALSE)
@gabrielcruzfer
Copy link

Add tryCatch to not have problems with errors.
Thanks for the coding!

for(i in 1:nrow(origAddress))
{
tryCatch({

Print("Working...")

result <- geocode(origAddress$addresses[i], output = "latlona", source = "google")
origAddress$lon[i] <- as.numeric(result[1])
origAddress$lat[i] <- as.numeric(result[2])
origAddress$geoAddress[i] <- as.character(result[3])
}, error=function(e){cat("Warning:",conditionMessage(e), "\n")})
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment