Split polygon parts of a single SpatialPolygons Object

元气小坏坏 提交于 2019-12-05 02:42:27

To separate multipolygon objects into single polygons (with holes if present) you can do

d <- disaggregate(p)

Where p is a SpatialPolygons object. After that, you can use d@polygons.

For example

library(sp)
library(raster)
### example data
p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
pols <- spPolygons(p1, p2, p3)
###

a <- aggregate(pols, dissolve=FALSE)
d <- disaggregate(a)

If your SpatialPolygons object is called mysp...

out <- lapply( mysp@polygons , slot , "Polygons" )

As I understand it, the OP wants to convert a SpatialPolygons object into a list of Polygons, preserving holes if present.

The SpP object created by the OP contains three polygons, the third of which has an associated hole.

You can use lapply to cycle through each polygon in SpP, returning a list of SpatialPolygons. The difference between a Polygons and SpatialPolygons object is the addition of plot order information. Since each resulting SpatialPolygons is of length = 1, however, this information is superfluous.

n_poly <- length(SpP)

out <- lapply(1:n_poly, function(i) SpP[i, ])

lapply(out, class)

> lapply(out, class)
   [[1]]
   [1] "SpatialPolygons"
   attr(,"package")
   [1] "sp"

   [[2]]
   [1] "SpatialPolygons"
   attr(,"package")
   [1] "sp"

   [[3]]
   [1] "SpatialPolygons"
   attr(,"package")
   [1] "sp"

plot(out[[3]]) # Hole preserved

If a list of Polygons is needed, simply pull the appropriate slot from the SpatialPolygons object:

out <- lapply(1:n_poly, function(i) SpP[i, ]@polygons[[1]])

lapply(out, class)

> lapply(out, class)
[[1]]
[1] "Polygons"
attr(,"package")
[1] "sp"

[[2]]
[1] "Polygons"
attr(,"package")
[1] "sp"

[[3]]
[1] "Polygons"
attr(,"package")
[1] "sp"

This will return a list of SpatialPolygons instead of ordinary Polygons (which some of the answers do).

SpP %>% split(1:length(.))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!