R计算重叠部分(多边形相交)的快速方法

Dav*_*vid 5 performance r

我正在寻找一种方法来计算基本多边形被另一个(选择)多边形覆盖的百分比。

以此为例。我想计算红色和蓝色的面积除以红色的面积。

group_a <- data.frame(x = c(1, 4, 1),
                      y = c(2, 4, 4),
                      group = "base")
group_b <- data.frame(x = c(2, 5, 2),
                      y = c(3, 3, 5),
                      group = "selection")

dat <- rbind(group_a, group_b)
dat
x y     group
1 1 2      base
2 4 4      base
3 1 4      base
4 2 3 selection
5 5 3 selection
6 2 5 selection

library(ggplot2)

ggplot(dat, aes(x = x, y = y, fill = group)) + geom_polygon(alpha = 0.5)
Run Code Online (Sandbox Code Playgroud)

rgdal一种方法是使用- 和- 包将 data.frames 更改为 Polygon rgeos,然后使用gAreagIntersection查找必要的值。但是,我认为这可能不是最快的方法。您知道计算面积/交叉点的更快方法吗?如果有一种RCpp方法可以做到这一点,我会特别高兴。

我希望我没有问太多;一如既往:感谢您的任何想法/提示!

情节1

编辑:这就是我对其他包的处理方式:

library(rgdal)
library(rgeos)
base <- group_a[, c("x", "y")]
sel <- group_b[, c("x", "y")]

base_pol <- Polygons(list(Polygon(base)), "base")
sel_pol <- Polygons(list(Polygon(sel)), "sel")

shape <- SpatialPolygons(list(base_pol, sel_pol))
plot(shape)

base_area <- gArea(shape["base"])
intersections <- gIntersection(shape["base"], shape["sel"])

gArea(intersections)/base_area
# [1] 0.4027778
Run Code Online (Sandbox Code Playgroud)

情节2

速度基准:运行microbenchmark,我得到以下结果:

OvPerc <- function(base, sel) {
  base <- base[, c("x", "y")]
  sel <- sel[, c("x", "y")]

  base_pol <- Polygons(list(Polygon(base)), "base")
  sel_pol <- Polygons(list(Polygon(sel)), "sel")

  shape <- SpatialPolygons(list(base_pol, sel_pol))
  # plot(shape)

  base_area <- gArea(shape["base"])
  intersections <- gIntersection(shape["base"], shape["sel"])

  return(gArea(intersections)/base_area)
}

library(microbenchmark)
microbenchmark(OvPerc(group_a, group_b), times = 1000)
# Unit: milliseconds
#                    expr      min       lq     mean   median       uq      max neval
# OvPerc(group_a, group_b) 3.680386 3.970394 4.932217 4.157952 4.745398 67.13696  1000
Run Code Online (Sandbox Code Playgroud)