Is there a way to convert a set of unordered lines in R (e.g. using terra
) into a polygon?
Here is an example:
library(terra)
geom <- as.matrix(data.frame(
"id" = rep(1:6,each = 2),
"x" = c(1,1,3,3,4,3,3,1,4,3,1,3),
"y" = c(2,3,1,2,2,2,4,3,2,4,2,1)
))
l <- vect(geom, type = "lines")
plot(l)
It does not need to be spatial polygon created in some package, I just want the coordinates to be arranged in a way that if I connect each point to the next point I get the polygon.
Here the required output for my example:
coords <- data.frame(
"x" = c(1,1,3,4,3,3,1),
"y" = c(2,3,4,2,2,1,2))
plot(coords)
lines(coords)
Edit: Thanks to the great answers, this is my solution when not using any additional packages.
geom$x <- geom$x - mean(geom$x)
geom$y <- geom$y - mean(geom$y)
geom$angle <- atan2(geom$x, geom$y)
geom <- unique(geom[order(geom$angle),])
geom <- rbind(geom, geom[1,])