Read an ESRI shapefile easily in R

Helloooo folks,

This blog has been silent for sometime, hopefully this is going to change smiley. I'm going to present a small function that makes reading shapefiles in R very easy. Over the years I've seen plenty of questions on how to read shapefiles in R and I've noticed that it can be confusing for some, at least it was for me. Get the code here http://www.rsnippet.com/?q=node/14

So let's get started:

1. Go to the page referenced above, copy and paste the entire code in a text editor and save it with the extension *.r (i. e. "readshape.r").

2. Launch R and source the code you just saved. Assuming readshape.r is in your working directory you can do it with the command source("readshape.r")

3. Now you should have 2 functions in your workspace: readshape and writeshape. You will need three R packages: tcltk, rgdal and sp. If you don't have them you can install them with install.packages("sp") , install.packages("rgdal") ... etc

4. Now to read a shapefile just issue the command: test<-readshape(), you should get a windows like below (if you don't see it it could be hidden behind other windows):

Navigate, choose a shapefile and click a Open. That's it! your file is read into the variable test

5. Now you can display it simply with plot(test)

6. You can also look at the data associated with the features:

> head(data.frame(test)) # Displays the first 6 only
  LATITUDE LONGITUDE ALTITU DEPTH WEATHERING DISCHARGE coords.x1 coords.x2
1  -7.5444    7.7333    400  37.6        8.2       1.6   -7.5444    7.7333
2  -7.3722    7.7194    500  41.5        8.5       2.4   -7.3722    7.7194
3  -7.0903    7.7125    300  45.0       22.8       1.8   -7.0903    7.7125
4  -7.0903    7.7125    300  49.5       28.7       3.0   -7.0903    7.7125
5  -7.0903    7.7125    300  80.5       18.7       2.5   -7.0903    7.7125
6  -7.0903    7.7125    300  58.5       13.5       9.0   -7.0903    7.7125

 

7. You can also write it back to a shapefile with:

> writeshape(test) # brings up another navigation window, see below

 

That's all folks!! At least for today