Search code examples
rgpc

Clipping polygons in R


I have two dataframes with geocodes. The first looks something like this:

spoints<- data.frame(x=c(1,2,3,4,5,6),y=c(6,5,4,3,2,1)) 

spoints maps a country.

My second data frame looks like this:

polyData<-data.frame(x=c(1,2,3,4,5,6,7,8,9,10),y=c(10,9,8,7,6,5,4,3,2,1),
col=c("a","b","c",etc.), id=c("a","b","c",etc.), average=c(44,33,66,55,etc))

This one contains coordinates to create voronoi clusters/polygons. but these are sketching polygons overlapping into the ocean. So, I want to avoid that and have them stop at the country boundaries.

But now, I am having difficulty using GPC library or the others.

Could someone please help me with this?


Solution

  • Here is an example using the rgeos library I mentioned in the comment.

    library(rgeos)
    library(sp)
    
    #making set of polygons for illustration
    d1 <- readWKT("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))")
    Tri <- c("POLYGON((0.3 0.6, 0.6 0.6, 0.5 1.3, 0.3 0.6))",
             "POLYGON((0.7 0.3, 1.3 0.3, 1.1 0.6, 0.7 0.3))")
    d2 <- readWKT(text=paste0("GEOMETRYCOLLECTION(",paste0(Tri,collapse=","),")"),
          id=c("a","b"))
    
    plot(d1,xlim=c(0, 1.4), ylim=c(0, 1.4))
    plot(d2,col='red',add=TRUE)
    
    #now taking the intersection
    d3 <- gIntersection(d1,d2,byid=TRUE)
    plot(d3,col='blue',add=TRUE)
    

    enter image description here