Search code examples
rpolygondivide

How to divide polygon in R?


I have a shapefile of Amazonas state (Brazil) and other with the six biggest rivers in this state (Negro, Solimões, Amazonas, Madeira, Purus and Juruá). I want to divide the state using the rivers, to get the interfluvial areas (Madeira-Purus, Purus-Juruá, etc). I want to get the final 6 regions delimited by those rivers, each region as a different polygon. How do I do that?

enter image description here

I'm only finding "clipping" algorithms, and those give me the area of the rivers that are inside the state, and that's not what I want.


Solution

  • Following @jbaums comment, I used gDifference, from package rgeos:

    intflv <- gDifference(state,rivers)
    

    but since "state" has only one polygon, intflv became a SpatialPolygons object with only one Polygon, made of thousands of sub-polygons. To work better in GIS software, I wanted it to be an object with all the thousands of Polygons, each as a single sub-polygon. So I did:

    l <- list()
    total <- length(intflv@polygons[[1]]@Polygons)
    for (i in 1:total) {
        print(paste(i,total,sep="/"))
        flush.console()
        P <- intflv@polygons[[1]]@Polygons[[i]]
        l[[length(l)+1]] <- Polygons(list(P),i)
    }
    sp <- SpatialPolygons(l)
    d <- data.frame(IDs=1:total)
    intflv1 <- SpatialPolygonsDataFrame(sp,data=d)
    writeOGR(intflv1,"shp","intflv","ESRI Shapefile")
    

    The result (after keeping only the biggest areas):

    enter image description here