More

How to export a dataset with “SpatialPolygonsDataFrame” as a shapefile

How to export a dataset with “SpatialPolygonsDataFrame” as a shapefile


How to export spatial datasets in R, such astornadosdataset inGISToolspackage, as a shapefile with the exact same spatial reference and the exact values?

library(GISTools) data(tornados)

Desired:

  • "SpatialPolygonsDataFrame" to "shapefile"
  • "(Forced) SpatialPointsDataFrame" to "shapefile"
  • "(Non-Forced) SpatialPointsDataFrame" to "shapefile"
  • "SpatialLinesDataFrame" to "shapefile".

Wesley's answer is correct. So to specifically export the tornado data you need to do:

library(GISTools) library(rgdal) data(tornados) writeOGR(obj=torn, dsn="tempdir", layer="torn", driver="ESRI Shapefile") # this is in geographical projection writeOGR(obj=torn2, dsn="tempdir", layer="torn2", driver="ESRI Shapefile") # this is in equal area projection

For R both of these datasets are simply treated as SpatialPointsDataFrames.

> class(torn) [1] "SpatialPointsDataFrame" attr(,"package") [1] "sp" > class(torn2) [1] "SpatialPointsDataFrame" attr(,"package") [1] "sp"

Note there is also a function in themaptoolspackage to accomplish this, namelywriteSpatialShape:

library(maptools) writeSpatialShape(torn, "torn").

See ?writeSpatialShape for options.


You should look at the rgdal package, specifically thewriteOGRfunction.

For example, I first downloaded the 110m-resolution "States and Provinces" shapefiles from Natural Earth, unpacking them to~/scratch/ne_110m_admin_1_states_provinces. I read them into R via:

library(rgdal) setwd("~/scratch") states <- readOGR(dsn="ne_110m_admin_1_states_provinces", layer="ne_110m_admin_1_states_provinces")

At this point, the objectstatesis aSpatialPolygonsDataFrame. Now I create a new directory ("tempdir") and save the shapefiles there:

dir.create("tempdir") writeOGR(obj=states, dsn="tempdir", layer="states", driver="ESRI Shapefile")

The shapes are now saved to the directory~/scratch/tempdir, as files states.shp, etc. You can do the same thing with aSpatialPointsDataFrame, just see the first example in the documentation of thewriteOGRfunction.


library(raster) shapefile(tornados, filename="path/to/file.shp")

Make sure you have (or have given yourself) permissions to write to the directory.