top of page

How to read and write shapefiles with R?

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") 
############################ 

img.png

Featured Posts
Check back soon
Once posts are published, you’ll see them here.
Recent Posts
Archive
Search By Tags
Follow Us
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square
bottom of page