Percentage of overlap between polygons

后端 未结 1 1111
青春惊慌失措
青春惊慌失措 2021-01-06 06:25

I\'m new to R and it\'s my first time posting here, thought to let you guys know I\'m still a newbie in the R language with the hope it will simplify your answers. I\'m curr

相关标签:
1条回答
  • 2021-01-06 06:31

    For the fun of it, here's an example. Some folks here or on gis.stackexchange.com might have better ways in petto:

    library(raster)
    library(sp)
    ## example data:
    p1 <- structure(c(0, 0, 0.4, 0.4, 0, 0.6, 0.6, 0), .Dim = c(4L, 2L), .Dimnames = list(NULL, c("x", "y")))
    p2 <- structure(c(0.2, 0.2, 0.6, 0.6, 0, 0.4, 0.4, 0), .Dim = c(4L, 2L), .Dimnames = list(NULL, c("x", "y")))
    p3 <- structure(c(0, 0, 0.8, 0.8, 0, 0.8, 0.8, 0), .Dim = c(4L, 2L), .Dimnames = list(NULL, c("x", "y")))
    poly <- SpatialPolygons(list(Polygons(list(Polygon(p1)), "a"),Polygons(list(Polygon(p2)), "b"),Polygons(list(Polygon(p3)), "c")),1L:3L)
    plot(poly)
    

    ## areas for the original shapes:
    areas_poly <- vector(length = length(poly)) 
    for (x in seq_along(poly)) areas_poly[x]<-area(poly[x])
    
    ## areas for the overlapping regions:
    idx <- combn(seq_along(poly),2)
    areas_intersect <- sapply(1:ncol(idx), function(x) {
      area(intersect(poly[idx[1,x]], poly[idx[2,x]])) 
    })
    
    ## get overlaps in percentages:
    overlap_perc <- 
      round(do.call(cbind, lapply(seq_len(ncol(idx)), function(x)  
      rbind(
        areas_intersect[x] / areas_poly[idx[1,x]] * 100, 
        areas_intersect[x] / areas_poly[idx[2,x]] * 100
      )
    )), 2)
    
    ## into matrix form:
    m <- matrix(100, ncol=length(poly), nrow=length(poly))
    m[rbind(t(idx),t(idx)[,2:1])] <- as.vector(t(overlap_perc))
    m
    #       [,1]   [,2] [,3]
    # [1,] 100.0  33.33  100
    # [2,]  50.0 100.00  100
    # [3,]  37.5  25.00  100
    
    0 讨论(0)
提交回复
热议问题