Shapefiles in R

I’ve posted before on this and I clearly didn’t know what I was doing. I still don’t really know what I’m doing but I now have some pretty pictures and that’s all anybody really wants. In this post I’m going to import a postcode shapefile from the OS, plot the postcodes in R, find the neighbours of each postcode and convert the data into a network graph. Github repository here.

First step. Import the OS shape file from here, I’ve only downloaded the sample data as I don’t have £3k to throw at a blog post. This was then imported using the package rgdal and function readOGR.

The shape file contains vertical streets for postcodes all in one building. For now I just exclude them from my code but that is not the best thing to do. What I should do is exclude the postcodes in a vertical street keeping only the vertical street. I’ll try and do that at a later date.

I then plotted the output so far

Which already looks far cooler than anything I did in my previous posts.

And going one step further I’ve calculated and plotted the postcode centroids

Without looking I’m guessing that the odd shapes of these postcodes could lead to the centroids not actually being inside the polygon. Maybe something for another day.

I now want to find all of the postcodes that border each postcode. To do this I used gTouches from the package rgeos. This creates a list of bordering postcodes for each postcode. After a bit of cleaning I have a dataset called Boundaries which is a list of pairs where each pair is a bordering postcode.

I now have a list of borders and a list of postcodes. I can now load these into a graph as per this guide by Katya Ognyanova. If I plot this network it looks like this.

Which looks pretty but doesn’t match the shape of the postcode boundaries in any way and there are an odd number of overlaps. But it is a start. After going back and adding in the postcode centroids into the net file and replotting I get this

Which does look very similar. I’ll leave overlaying the two plots for another day along with doing some analysis on this.

Leave a Reply

Your email address will not be published. Required fields are marked *