I am trying to return the area of each polygon (of a multipolygon) which is not overlapping another. When looking at the image below, I would like to return a polygon of just the red part (left side of image), with the blue part removed.
I understand that I could find the intersection using gIntersect
or raster::intersect
, but the problem is that these circles are part of a single SpatialPolygonDataFrame
. Disaggregating the circles is not really an option, I don't think, because my SpatialPolygonDataFrame
contains more than 18,000 polygons.
I've provided a sample of reproducible code below (adapted from Cotton.Rockwood on this post. Thank you!
box <- readWKT("POLYGON((-180 90, 180 90, 180 -90, -180 -90, -180 90))")
proj4string(box) <- CRS("+proj=cea +datum=WGS84")
set.seed(1)
pts <- spsample(box, n=10, type="random")
pols <- gBuffer(pts, byid=TRUE, width=50) # create circle polys around each point
merge = sample(1:40, 10, replace = T) # create vector of 100 rand #s between 0-40 to merge pols on
Sp.df1 <- gUnionCascaded(pols, id = merge) # combine polygons with the same 'merge' value
# create SPDF using polygons and randomly assigning 1 or 2 to each in the @data df
Sp.df <- SpatialPolygonsDataFrame(Sp.df1,
data.frame(z = factor(sample(1:2, length(Sp.df1), replace = TRUE)),
row.names= unique(merge)))
plot(Sp.df, col='blue')
i <- gDifference(Sp.df, Sp.df, byid=T)
plot(i, col='red')