多边形之间重叠的百分比

时间:2017-04-29 09:44:53

标签: r

我是R的新手,这是我第一次在这里发帖,想让你们知道我还是R语言的新手,希望它能简化你的答案。我目前正在做我的硕士论文,其中包括很多关于包含南非不同物种分布的shapefile的工作。我的研究包括4个动物家族; 1个猎物家族(由29种物种组成)和3个捕食性家庭(每个包含更多物种)。对于每个物种,我有一个shapefile,其分布为多边形,所以我有很多shapefile。我现在的问题是,我必须计算每个捕食者与每个猎物种类的重叠百分比(100%重叠是捕食者的分布/多边形在猎物的分布/多边形内,因此百分比应相对于猎物种类的多边形)。

我知道我可以分别为每个物种逐一做这个,但这实际上花了我几个星期而且我没有时间。甚至我在大学的发起人也没有做过这样的事情,并试图弄清楚自己。他最初给了我这段代码:

my_rangemaps <- list.files(path = "imagine_rangemaps", pattern = ".shp", full.names = TRUE) 
my_rangemaps 
rangemap_matrix <- pairwiseRangemaps(my_rangemaps, projection = 3035, 
             Ncpu = 1, nchunks = 1, filename = "rangemap_matrix.csv") 

但结果不是我们所期望的,因为它没有计算相对于任何多边形的百分比。有没有人知道使用相对简单的代码获得重叠百分比的方法而没有太多的模糊?可能导致包含所有物种/形状文件/多边形的矩阵形式?

提前谢谢大家!

1 个答案:

答案 0 :(得分:5)

为了它的乐趣,这是一个例子。这里或gis.stackexchange.com上的一些人可能在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)

enter image description here

## 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