问题
I am looking for a way to calculate the percentage a base-polygon is overlayed by another (selection) polygon.
Take this as an example. I want to calculate the area of red AND blue over the area of red.
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)
One way would be to change the data.frames to a Polygon using the rgdal
- and rgeos
-packages, and then use gArea
and gIntersection
to find the neccessary values. However, I assume that this might not be the fastest way to do this. Do you know a faster way to calculate the areas/intersections? I would be especially delighted if there is an RCpp
-way to do it.
I hope I haven't asked too much; and as always: Thank you for any ideas/hints!
Edit: This is how I would do it with the other packages:
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
Speed Benchmark: Running microbenchmark
, I obtained the following results:
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
来源:https://stackoverflow.com/questions/35039614/r-calculate-overlapping-section-polygon-intersection-the-fast-way