9

Does anyone know how to calculate the area in common between 2 or more polygons in R? I would like to have the output of such a calculation be the coordinates of a new polygon for that area of overlap. Cheers

Marc in the box
  • 11,769
  • 4
  • 47
  • 97

2 Answers2

13

EDIT: these days I would use the 'intersect', 'cover', 'erase', 'union' and related functions in the 'raster' package. They do the hard work to keep the top-level object and attributes.

ORIG: You could use the rgeos package with its gIntersection function. Successive calls between pairs and resulting intersections will get you there. See

library(rgeos)
?gIntersection

You will need to get into the structure of "SpatialPolygons" in the sp package to get the final coordinates. See the vignette("sp").

mdsumner
  • 29,099
  • 6
  • 83
  • 91
  • 1
    Thanks for the tips. they steered me in the right direction. Will have to try out some other packages, but PBSmapping has a pretty straightforward way to do what I needed: library(PBSmapping) p1 <- data.frame(PID=rep(1, 4), POS=1:4, X=c(1,1,6,6), Y=c(1,3,3,1)) p2 <- data.frame(PID=rep(2, 5), POS=1:5, X=c(4,4,8,8,6), Y=c(2,4,4,2,1)) p3 <- joinPolys(p1,p2) plot(1,1,ylim=c(0,10),xlim=c(0,10), t="n") polygon(p1$X, p1$Y, border=2) polygon(p2$X, p2$Y) polygon(p3$X, p3$Y, col=rgb(0,0,1,0.2)) – Marc in the box Apr 02 '12 at 13:45
10

Just thought I would add the solution that I eventually used - the joinPolys function from the PBSmapping package.

Example:

library(PBSmapping)
p1 <- data.frame(PID=rep(1, 4), POS=1:4, X=c(1,1,6,6), Y=c(1,3,3,1))
p2 <- data.frame(PID=rep(2, 5), POS=1:5, X=c(4,4,8,8,6), Y=c(2,4,4,2,1))
p3 <- joinPolys(p1,p2)
x11()
par(mar=c(3,3,1,1))
plot(1,1,ylim=c(0,5),xlim=c(0,9), t="n", xlab="", ylab="")
polygon(p1$X, p1$Y, border=2)
polygon(p2$X, p2$Y)
polygon(p3$X, p3$Y, col=rgb(0,0,1,0.2))

enter image description here

Community
  • 1
  • 1
Marc in the box
  • 11,769
  • 4
  • 47
  • 97
  • 1
    Hi @Marc in the box. I was searching for a answer to my question: How to calculate the non-overlapping area between two center aligned arbitrary polygon (with no holes) using R? It seems to me that your question is similar to me (though I want to have "complement area"), but I could not solved it. I want the area (scalar unit). Could you please help me in this direction. Thanks in advance. – Janak Mar 20 '15 at 12:22
  • @Mark, amazing - exactly what I need. Thanks for posting your solution! – adilapapaya Sep 14 '16 at 00:21