[R-sig-Geo] converting hierarchical clusters to polygons

Kent Johnson kent3737 @ending from gm@il@com
Mon May 28 15:39:03 CEST 2018


On Mon, May 28, 2018 at 6:00 AM, <r-sig-geo-request using r-project.org> wrote:

> From: "Bannar-Martin, Katherine"
>         <Katherine.Bannar-Martin using dfo-mpo.gc.ca>
> To: "r-sig-geo using r-project.org" <r-sig-geo using r-project.org>
> Subject: [R-sig-Geo] converting hierarchical clusters to polygons
> Message-ID:
>         <C58761628CE59340834AA8638074761A2785BE using DFBCV6CWPEXP001.ENT.
> dfo-mpo.ca>
>
> Content-Type: text/plain; charset="utf-8"
>
> I have used hierarchical clustering to assign lats and longs (start and
> end positions of lines) to separate cluster IDs.
> I now need to convert each cluster of points to a polygon.
>


> I have 100s of clusters per year (13 years) so I do not want to have 1000s
> of separate polygon files, but instead one layer with all the polygons per
> year.
>
> Dummy data to show approximate structure:
> GISID     x             y             Attribute              Year
>  CLUSTER_ID
> 1             -129.24 52.994   Start                     2005      1
> 2             -131.26 52.73     Start                     2006      33
> 3             -126.02 49.297   End                       2005      5
>

This uses tidyverse and sf to find the convex hull of points in each
cluster and create a simple features object with one row per polygon. It
retains the Year and CLUSTER_ID so you can select by year and show all
clusters or write one file per year.

library(tidyverse)
library(sf)

d = read_table2(col_names=TRUE,
file="GISID     x             y             Attribute              Year
   CLUSTER_ID
1             -129.24 52.994   Start                     2005      1
2             -131.26 52.73     Start                     2006      33
3             -126.02 49.297   End                       2005      5")

groups = d %>%
  select(-GISID, -Attribute) %>%
  nest(x, y) %>%
  mutate(poly = map(data, ~st_convex_hull(st_multipoint(as.matrix(.[,c('x',
'y')]))))) %>%
  select(-data) %>%
  st_sf()

# For example to plot all polygons for one year, colored y CLUSTER_ID:
groups %>% filter(Year==2006) %>% select(-Year) %>% plot()

HTH,
Kent Johnson

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list