[GIS] Converting points to polygons by group

rsftypecast

I have a dataframe with around 40 points. They are grouped by an ID variable (their name), which four points in each group. I'm trying to turn these points into polygons, but I've had a lot of trouble with different methods in both sf and sp — currently I have them as a large sf dataframe, but I can't seem to find any function that would use a grouping variable to create polygons.

I've tried using the st_cast method, the general idea being

polypoints <- polypoints %>% 
    group_by("ID") %>% 
    st_cast("MULTIPOINT") %>% 
    st_cast("MULTILINESTRING") %>% 
    st_cast("MULTIPOLYGON")

but the step from multipoint to multiline string leaves the geography empty — what are the steps for a process like this?

Best Answer

You need to summarise after your group_by statement then your approach works perfectly fine. Directly from POINTS --> POLYGON, and keeping the crs (if there is one).

set.seed(999)
xy = data.frame(x=runif(24), y=runif(24))
xy$ID = rep(1:6, each = 4)
head(xy)

xys = st_as_sf(xy, coords=c("x","y"))

polys = xys %>% 
  dplyr::group_by(ID) %>% 
  dplyr::summarise() %>%
  st_cast("POLYGON")

plot(polys)

enter image description here

If you want the outer polygon you can add st_convex_hull()

polys = polys %>% 
  st_convex_hull()

plot(polys)

enter image description here