Search This Blog

Sunday, August 9, 2015

Reading shape files in R

In the previous post, we saw how to read dbf files in R. I wanted to go a step further.

I was looking at ways to read shape file data in R. It turns out there are various mechanisms for doing just that. However, for the library to be installed correctly, your environment needs to be setup correctly.

Here are the steps I followed.

1. Install libgdal
2. Install libproj
3. Install rgdal package
4. Test loading a shape file

The following script should install these packages correctly for you.

sudo apt-get install apt-file
sudo apt-get update
sudo apt-get install libgdal1h
sudo apt-get install libgdal1-dev libproj-dev

Once these packages are setup correctly start R as sudo

sudo R

Enter the following commands on the R console

install.packages("rgdal")
install.packages("rgeos")
install.packages("ggmap")
install.packages("maptools")
q()


The following screen shows installation for rgeos


Next run the following commands in R (without sudo)

library(rgdal)
shpfilepath="../data/shpfiles"
ogrInfo(shpfilepath,"fatality_yearly")
ftlty_yr <-readOGR(shpfilepath, "fatality_yearly")
This shows the following:


Now, enter the following command in R

plot(ftlty_yr, axes=TRUE, border="gray")


Our R environment can now read shapefiles correctly

No comments: