首页 > 解决方案 > 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")

标签: rrastershapefile

解决方案


发生错误是因为您有 SpatialPolygons,而不是 SpatialPolygonsDataFrame 对象。解决此问题的一种简单方法是改用该shapefile函数。

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

shapefile(p, "xyz_extent.shp")

您可以使用相同的功能再次读取文件

x <- shapefile("xyz_extent.shp")

推荐阅读