Convert polygons to points or lines in R
We often need to simplify the geometry of polygons into points or lines. How do you do that in R? Nothing easier than that – we resort to the functions gCentroid or gPointOnSurface from the rgeos library.
Let’s first load the libraries for reading and transforming vector data:
library(rgdal) library(rgeos)
Next, we load our polygons. We will use the boundaries of the municipalities in Mazovia from the Polish Register of Borders (download):
polygons <- readOGR("d:/m_maz.shp")
Show loaded layer:
plot(polygons)
We can use gCentroid to create the centroids of the polygons:
centroids <- gCentroid(polygons, byid = T)
Let’s add the centroids to the previously displayed layer:
plot(centroids,add=T, pch = 20, col = "red")
In the rgdal library, there is another function for generalizing polygons to points – gPointOnSurface. This function is a bit slower, but it always creates points inside polygons, unlike gCentroid. Let’s create a layer with this tool:
pos <- gPointOnSurface(polygons, byid = T)
Let’s add the result to the layers shown earlier:
plot(pos,add = T, pch = 20, col = "green")
As you can see, the points from both point layers are offset from each other.
Finally, we show how to convert the polygons into lines. To do this, we use the class Projection with the base function R as:
lines <- as(polygons, "SpatialLinesDataFrame")
We check the class of the new object:
> class(lines) [1] "SpatialLinesDataFrame" attr(,"package") [1] "sp"
We have a line layer 🙂