I want to take a line and use it to split a polygon into multiple polygons, or to create two separate named region in the original polygon (if that's possible). The end goal would be having points that fall into one of the two regions and then plot the polygons where fill = number of points in the region.
I have tried using sf for a while and also terra. Any method of doing this would be appreciated.
library(sf)
# create a polygon and a line
poly <- st_polygon(list(rbind(c(0, 0), c(1, 0), c(1, 1), c(0, 1), c(0, 0))))
line <- st_linestring(rbind(c(0.5, -0.5), c(0.5, 1.5)))
# plot the polygon and line
plot(poly)
plot(line, add = TRUE)
# split the polygon into two using the adjusted line
poly_split <- st_intersection(poly, line)
# plot the two resulting polygons
plot(poly_split)
For this simple case, you could do
library(terra)
splitp <- function(pol, lin) {
x <- rbind(as.lines(pol), lin)
a <- aggregate(x)
m <- makeNodes(a)
as.polygons(m)
}
library(terra)
poly <- vect(rbind(c(0, 0), c(1, 0), c(1, 1), c(0, 1), c(0, 0)), "poly")
line <- vect(rbind(c(0.5, -0.5), c(0.5, 1.5)), "line")
p <- splitp(poly, line)
plot(p, col=c("blue", "red"))
With terra 1.7-23 (currently the development version) you can use split
library(terra)
# terra 1.7.23
poly <- vect(rbind(c(0, 0), c(1, 0), c(1, 1), c(0, 1), c(0, 0)), "poly")
line <- vect(rbind(c(0.5, -0.5), c(0.5, 1.5)), "line")
p <- split(poly, line)
plot(p, col=c("blue", "red"))