How to use R-package ‘rgdal’ to read shapefiles

rgdal

This tutorial contains an example on how to read, access and plot ESRI shapefiles in R by using the R-package rgdal.

Rgdal provides bindings to Frank Warmerdam’s Geospatial Data Abstraction Library (GDAL).

Dependencies
depends on R library ‘sp’
‘gdal-config’ has to be installed on the computer

#!/bin/bash
sudo apt-get install libgdal1-dev
sudo apt-get install libgdal1-dev libproj-dev

Reference manual
http://cran.r-project.org/web/packages/rgdal/rgdal.pdf

Example
For further information about the data which is used in this example please visit: http://www.naturalearthdata.com/downloads/10m-cultural-vectors/10m-admin-0-countries/

# Install Packages
install.packages('rgdal')

# Load 'rgdal' library in R
library(rgdal)

# Download Shapefile
url.c='http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/10m/cultural/ne_10m_admin_0_countries.zip'
dfile='ne_10m_admin_0_countries.zip'
download.file(url.c, destfile=dfile, method='wget')

# Unzip Shapefile
unzip('ne_10m_admin_0_countries.zip', exdir='countries')
#Remove .zip file
file.remove('ne_10m_admin_0_countries.zip')

# Read Shapefile of Countries
cshp=readOGR('countries', 'ne_10m_admin_0_countries')

# Plot all Polygons in rainbow-color
plot(cshp,col=rainbow(nrow(cshp)),border='grey')
title('Countries of the World')
mtext('Source:\n http://www.naturalearthdata.com/downloads/10m-cultural-vectors/10m-admin-0-countries/',side=1)

# Add Australia in grey color
au=which(cshp@data$NAME=='Australia')
plot(cshp[au,],col='grey',border='black',add=T)

# Coordinates of first Australian polygon (au)
cshp@polygons[[au]]@Polygons[[1]]@coords

# Min and Max of Lat and Lon
cshp[au,]@bbox