I have a shapefile (which can be downloaded here http://www.car.gov.br/publico/municipios/downloads?sigla=MA (any would do)) where each polygon represent a rural private property, as the owner submited it. However, the polygons overlap. For the analysis I need to run, an area cannot be accounted twice (ie. be in two properties ). So, on the areas that do overlap, I wanted to assign this duplicate area to the polygon with the smallest area and erase it from the other one.
I've looked at other questions such as this one. But none do really adress this.
You can do this by subtracting the smaller polygon from the larger using rgeos::gDifference
.
An example:
First we make some dummy polygons to demonstrate on
library(sp)
library(rgeos)
p1 <- Polygon(matrix(c(
100, 100,
100, 500,
900, 500,
900, 100,
100, 100), ncol=2, byrow = T))
p2 <- Polygon(matrix(c(
50, 400,
50, 600,
800, 600,
800, 400,
50, 400), ncol=2, byrow = T))
p1 <- SpatialPolygons(list(Polygons(list(p1), "p1")))
p2 <- SpatialPolygons(list(Polygons(list(p2), "p2")))
plot(p1)
plot(p2, add=T)
We can use gArea
to find which is smaller
a1 = gArea(p1)
## [1] 320000
a2 = gArea(p2)
## [1] 150000
Now we can remove the intersection from the larger polygon with like this:
if (a1>a2){
p3 = gDifference(p1,p2)
p4 = p2
} else {
p3 = gDifference(p2,p1)
p4 = p1
}
plot(p3)
The two polygons together look like this
plot(p4, add=T)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With