Reputation: 1009
I'd like to create polygons with st_voronoi and merge them by a variable
library(sf)
nc_centroids <- st_transform(nc_centroids,crs=32119)
nc_centroids$foo <- c(rep("green",50),rep("red",50))
nc <- st_transform(nc,crs=32119)
v <- st_voronoi(st_union(nc_centroids))
plot(v, col = 0)
plot(st_intersection(st_cast(v), st_union(nc)), col = 0)
plot(nc_centroids, add = TRUE)
How might I merge the polygons in v by nc_centroids$foo to create two big polygons? I can think of some hacks, like using lapply to join the individual polygons of v, e.g., (v[[1]][[x]]). But surely there's something easier
Upvotes: 2
Views: 334
Reputation: 4652
Please find below a reprex that details one possible approach.
Reprex
library(sf)
library(dplyr)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc_centroids <- st_centroid(nc)
nc_centroids <- st_transform(nc_centroids,crs=32119)
nc_centroids$foo <- c(rep("green",50),rep("red",50))
nc <- st_transform(nc,crs=32119)
v <- st_voronoi(st_union(nc_centroids))
v <- v %>%
st_collection_extract(., "POLYGON") %>%
st_as_sf()
v_result <- v %>%
st_join(., nc_centroids, st_intersects) %>%
group_by(foo) %>%
summarize()
nc_result <- nc %>%
st_join(., v_result) %>%
group_by(foo) %>%
summarize()
plot(nc_result)
Created on 2022-02-07 by the reprex package (v2.0.1)
Upvotes: 4