问题
How to add an polygon to a SpatialPolygonsDataFrame?
Example: The script underneath will create a SpatialPolygonsDataFrame. I would like to add a polygon which consists of a large square around the existing polygons.
library(rgdal)
dsn <- system.file("vectors", package = "rgdal")[1]
Scotland <- readOGR(dsn=dsn , layer="scot_BNG")
plot(Scotland)
Preferred end result:
It is important that the rectangle becomes part of the SpatialPolygonsDataFrame. Since I have to do some calculation of the dataframe. So manually adding a visual layer of a square is insufficient.
Thanks!
回答1:
The following code creates a rectangle that encloses the original spatial polygons and adds this as a spatial polygon to the original shape.
library(rgdal)
library(rgeos)
dsn <- system.file("vectors", package = "rgdal")[1]
Scotland <- readOGR(dsn=dsn , layer="scot_BNG")
# change the width parameter to make the rectangle the desired size
# this results in an extent object that surrounds the original shape
eScotland <- extent(gBuffer(Scotland, width = 50000))
# turn the extent into a Spatial Polygon
pScotland <- as(eScotland, 'SpatialPolygons')
crs(pScotland) <- crs(Scotland)
newScotland <- bind(pScotland, Scotland)
plot(newScotland)
来源:https://stackoverflow.com/questions/59933458/adding-a-polygon-to-a-spatialpolygonsdataframe