Calculate area overlap for pairs of polygons in matrix format in R

Viewed 1356

I am trying to calculate the area and percentage of overlap between polygons for multiple pairs. For example, I have 5 polygons and I want to calculate the area and percentage of overlap for each combination of pairs. Is there a way I can run a function including all polygons (shapefiles) and get a matrix output showing the values for each pair? I would like to get an output like this:

overlap    poly 1     poly 2    poly 3     poly 4 poly 5

poly 1

poly 2

poly 3

poly 4

poly 5

The formula I use to calculate percentage of overlap for a pair of polygons is the following:

AreaOverlap/(SQRT(AreaPolyA*AreaPolyB))

Thanks!

1 Answers

Without sample data, i think a possible solution can be:

create some sample data

library( sf)
#square of 2 x 2
pol = st_polygon(list(rbind(c(0,0), c(2,0), c(2,2), c(0,2), c(0,0))))
#add two more squares of 2 x 2
b = st_sfc(pol, pol + c(.8, .2), pol + c(4, .8))

plot(b)

enter image description here

calculate overlapping area

l <- lapply( b, function(x) { 
       lapply(b, function(y) st_intersection( x, y ) %>% st_area() ) 
     })

matrix(unlist(l), ncol = length(b), byrow = TRUE)
#      [,1] [,2] [,3]
# [1,] 4.00 2.16    0
# [2,] 2.16 4.00    0
# [3,] 0.00 0.00    4

calculate overlapping percentage

l2 <- lapply( b, function(x) { 
  lapply(b, function(y) st_intersection( x, y ) %>% st_area() * 100 /sqrt( st_area(x) * st_area(y) ) ) 
})

matrix(unlist(l2), ncol = length(b), byrow = TRUE)
#      [,1] [,2] [,3]
# [1,]  100   54    0
# [2,]   54  100    0
# [3,]    0    0  100
Related