1. Demonstration of how to read and write ESRI
Shapefiles in R, including points, lines, and polygons.
Sazid Ibna Zaman
Data Manager & GIS Specialist
MEEM Project
MORU & NMCP
2. Requirements
Rstudio installed
Packages(rgdal, RColorbrewer,sp)
rgdal: Bindings for the Geospatial Data Abstraction Library
translator library for raster and vector geospatial data formats
RColorBrewer: Color brewer pallates
sp: Classes & Methods for spatial data
Shape File
Boundary, Roadline, Community Clinic
Notes
The rgdal approaches produce Spatial DataFrame objects in R, as defined in the 'sp'
package.
3. read-write-shapefiles.R
R code intended as a basic demonstration of how to read and write ESRI Shapefiles in R,
including points, lines, and polygons.
Input Data
Administrative Boundary
Polygon shapefile of Ramu Upazila in Cox’s Bazar District
Community Clinic
Point shapefile of community clinic of that region
Rodeline
Line shapefile of major roads in that region
Output
* Copy of the region point, line, polygon shapefile, written out by rgdal functions.
* Map visualization .
4. Codes to read-write-shapefiles.R
# read in shapefiles
centroids.rg <- readOGR(".", "Ramu_CC")----Community Clinic
road.rg <- readOGR(".", "Ramu_RoadLine")----Road Line
counties.rg <- readOGR(".", "Ramu_UnBnd")----Administrative Boundary
# note that readOGR will read the .prj file if it exists
print(proj4string(counties.rg))
# set up colors:RColorBrewer
plotclr <- brewer.pal(11,"BrBG")
plotvar <-counties.rg@data$Union_NM
class <- classIntervals(plotvar)
colcode <- findColours(class, plotclr)
5. Codes to read-write-shapefiles.R
# generate a simple map showing all three layers
1. Plotting Administrative Boundary
plot(counties.rg, axes=TRUE, col=plotclr, border="black")
2. Showing labels
text(coordinates(counties.rg),labels=paste(plotvar),pos=1,c
ex=.5,col="white")
3. Plotting Road Lines
lines(road.rg, col="red", lwd=1.0)
4. Plotting Community Clinic
points(centroids.rg, pch=20, col="yellow",cex=1.5)
5. Title of the map
title(main="Assessing the contribution of migration to the
emergence and spread of antimalarial drug resistance in
Bangladesh")
legend("bottomright","Community Clinic of Ramu Upazila")
6. Legend of the map
legend("topleft",c("Road Line","Community Clinic"),
lwd=c(3,3),col=c("red","yellow"),title = "Legend",cex =
.75,bty = "y") # border
1
2
3
4
5
6