performance - R Calculate overlapping section (polygon intersection) the fast way -
i looking way calculate percentage base-polygon overlayed (selection) polygon.
take example. want calculate area of red , blue on 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 change data.frames polygon using rgdal
- , rgeos
-packages, , use garea
, gintersection
find neccessary values. however, assume might not fastest way this. know faster way calculate areas/intersections? delighted if there rcpp
-way it.
i hope haven't asked much; , always: thank ideas/hints!
edit: how 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
, obtained 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
Comments
Post a Comment