How to read and write shapefiles with R?

June 23, 2015

It is important to know how to work with shapefiles in R to access incredible functionality and analytic ability--much of which is unavailable in many GIS software packages. Of course, working with spatial data in an open source environment is always good! 

 

The following example reads a shapefile, runs a geometry simplification algorithm and writes the simplified polygons back to shapefile format.

 

############################

require(rgdal)

require(rgeos)

 

# Read shapefile

shp = 'C:/temp/myshp.shp'

myshp = readOGR(shp, layer = basename(strsplit(shp, "\\.")[[1]])[1])

 

# Read shapefile attributes

df = data.frame(myshp)

 

# Simplify geometry using rgeos

simplified = gSimplify(myshp, tol = 1000, topologyPreserve=FALSE)

 

# Create a spatial polygon data frame (includes shp attributes)

spdf = SpatialPolygonsDataFrame(simplified, df)

 

# Write to shapefile

writeOGR(spdf, layer = 'myshp_simplified', 'C:/temp', driver="ESRI Shapefile")

############################

 

 

 

 

Please reload

Featured Posts

I'm busy working on my blog posts. Watch this space!

Please reload

Recent Posts
Please reload

Archive
Please reload

Search By Tags
Please reload

Follow Us
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square

© Red Fox GIS & Remote Sensing