简体   繁体   中英

R and Export raster extent as esri shapefile

I am working with a raster dataset in R and would like to make a polygon of its extent and then export this as an ESRI shapefile. My problem, or at least what I think is the problem, occurs when I try to export the spatial polygon dataframe as I get the following error:

Error in writeOGR(p, ".", "xyz_extent", driver="ESRI Shapefile") : obj must be a SpatialPointsDataFrame, SpatialLinesDataFrame or SpatialPolygonsDataFrame

My script follows. Please note, I have a beginner skillset when working with spatial data in R so I do ask that answers be well described. Thank you in advance to those that chime in.

Script:

library(raster)
xyz <- raster("xyz.asc")
crs(xyz)
# CRS arguments: +proj=tmerc +lat_0=0 +lon_0=-115 +k=0.9992 +x_0=500000  +y_0=0 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0 

e <- extent(xyz)
p <- as(e, 'SpatialPolygons')
crs(p) <- crs(xyz)

library(rgdal)
writeOGR(p, ".", "xyz_extent", driver="ESRI Shapefile")

The error occurs because you have a SpatialPolygons, not a SpatialPolygonsDataFrame object. An easy way around this is to use the shapefile function instead.

library(raster)
xyz <- raster()
e <- extent(xyz)
p <- as(e, 'SpatialPolygons')
crs(p) <- crs(xyz)

shapefile(p, "xyz_extent.shp")

And you can read the file again with the same function

x <- shapefile("xyz_extent.shp")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM