I have a data frame like following:
long lat group
1.0 1.0 1
1.0 2.0 1
2.0 2.0 1
5.0 5.0 2
5.0 6.0 2
6.0 6.0 2
How can I convert it into a list of polygon objs?
Thanks!
I have a data frame like following:
long lat group
1.0 1.0 1
1.0 2.0 1
2.0 2.0 1
5.0 5.0 2
5.0 6.0 2
6.0 6.0 2
How can I convert it into a list of polygon objs?
Thanks!
Your sequences of points aren't closed, so in sf, you'd need to munge a bit to turn them into polygons. One option is to make a multipoint object and cast to polygon:
library(tidyverse)
library(sf)
df <- data.frame(long = c(1, 1, 2, 5, 5, 6),
lat = c(1, 2, 2, 5, 6, 6),
group = c(1L, 1L, 1L, 2L, 2L, 2L))
df_sf <- df %>%
group_by(group) %>%
summarise(geometry = st_sfc(st_cast(st_multipoint(cbind(long, lat)), 'POLYGON'))) %>%
st_sf()
df_sf
#> Simple feature collection with 2 features and 1 field
#> geometry type: POLYGON
#> dimension: XY
#> bbox: xmin: 1 ymin: 1 xmax: 2 ymax: 2
#> epsg (SRID): NA
#> proj4string: NA
#> # A tibble: 2 x 2
#> group geometry
#> <int> <POLYGON>
#> 1 1 ((1 1, 1 2, 2 2, 1 1))
#> 2 2 ((5 5, 5 6, 6 6, 5 5))
ggplot(df_sf) + geom_sf()