I have a dataframe containing the coordinates of a set of polygons. This is how I would convert it to a spatialPolygons (package sp)
my.df <- data.frame(
Plot = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"),
Corner = c("SW", "NW", "NE", "SE", "SW2", "SW", "NW", "NE", "SE", "SW2"),
Easting = c(511830, 512230, 512230, 511830, 511830, 511730, 512130, 512130, 511730, 511730),
Northing = c(7550903, 7550903, 7550503, 7550503, 7550903, 7550803, 7550803, 7550403, 7550403, 7550803))
utm18 <- CRS("+init=EPSG:26918")
my.sp <- df_to_SpatialPolygons(my.df, keys = "Plot", coords = c("Easting", "Northing"), utm18)
plot(my.sp)
How can I create an sf object (package sf) containing these two polygons directly from my.df?
Edit: My question is partially answered in this question, but their response only illustrates how to create a single polygon. How do I create multiple polygons?
Convert sequence of longitude and latitude to polygon via sf in R
library(sfheaders)
lets you construct an sf object from a data.frame directly
library(sf)
library(sfheaders)
sf <- sfheaders::sf_polygon(
obj = my.df
, x = "Easting"
, y = "Northing"
, polygon_id = "Plot"
)
sf::st_crs( sf ) <- 26918
sf
# Simple feature collection with 2 features and 1 field
# geometry type: POLYGON
# dimension: XY
# bbox: xmin: 511730 ymin: 7550403 xmax: 512230 ymax: 7550903
# z_range: zmin: NA zmax: NA
# m_range: mmin: NA mmax: NA
# CRS: EPSG:26918
# id geometry
# 1 1 POLYGON ((511830 7550903, 5...
# 2 2 POLYGON ((511730 7550803, 5...
plot( sf )
I figured out an answer based on paqmo's suggestion to look at Convert sequence of longitude and latitude to polygon via sf in R
The answer provided in that question groups all the points in the data frame as a single polygon. I've added a step to group the dataframe by the variable that identifies the polygon.
polygon <- my.df %>%
st_as_sf(coords = c("Easting", "Northing"), crs = utm18) %>%
group_by(Plot) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("POLYGON")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With