Site icon R-bloggers

Fun with geocoding and mapping in JGR

[This article was first published on NERD PROJECT » R project posts, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

For a recent project I had to do some mapping of addresses, but I didn’t have there lat/lons do use the Deducer and DeducerSpatial packages in R JGR.  After frustrating myself trying to adapt this code from stackoverflow.com, I found a much easier way of geocoding using the dismo and XML packages in R.

First you need to have the complete address in one column or vector, so that Google will give you the right right coordinates.  Since Address, City , and State were all in different columns, I used the paste function to put them in a new column name “location” ( this is strategic for purposes you will see later) using the following code:

mls$location<-paste(mls$address, mls$city, mls$state, sep = ",")

Now you can open and run the geocode on the new variable, like this:

library(c("dismo", "XML")) loc<-geocode(data$address, oneRecord=TRUE, progress = "text")

The new data.frame, loc, will be structured like this:

  ID lon      lat      lonmin    lonmax    latmin   latmax 1 1 -75.17598 39.93971 -75.17733 -75.17463 39.93836 39.94106 2 2 -75.12525 40.04373 -75.12660 -75.12390 40.04238 40.04508 3 3 -75.11745 40.03415 -75.11880 -75.11610 40.03280 40.03550 4 4 -75.15250 39.93793 -75.15385 -75.15115 39.93658 39.93928 5 5 -74.98711 40.04627 -74.98846 -74.98576 40.04492 40.04762 location 1 1017 S 20th St B,Philadelphia,PA 2 267 W Spencer St,Philadelphia,PA 3 305 E Gale St,Philadelphia,PA 4 522 Queen St,Philadelphia,PA 5 45304 Delaire Landing Rd 304,Philadelphia,PA

Because the full address variable is named the same in both data$location and loc$location, you can merge the two data.frames by the location variable using the merge function:

data<-merge(data, loc, all=TRUE)

Now you map observations in R JGR, downloaded from here, after installing and opening the Deducer and DeducerSpatial packages.  First you need to convert the data.frame under the spatial tab, and then go to the spatial plot builder.  Once in the plot builder, you can plot based on any variable in your dataset.  When your happy with your map and plot, just hit run and it will save it and give you an output like this:


To leave a comment for the author, please follow the link and comment on their blog: NERD PROJECT » R project posts.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.