From https://observablehq.com/@jwolondon/gridmap-allocation. Returns an LP solution allocating 2D points to a grid.
Usage
points_to_grid(pts, n_row, n_col, compactness = 1, spacers = list())
Arguments
- pts
tibble of geographic points (x,y) to be allocated to a grid.
- n_row
maximum number of rows in grid.
- n_col
maximum number of columns in grid.
- compactness
Optional parameter between 0 and 1 where 0 allocates towards edges, 0.5 preserves scaled geographic location and 1 allocates towards centre of grid. Default is 1 (compact cluster).
- spacers
Optional list of grid cell locations defining grid location of fixed spacers which cannot be allocated points. Coordinates are in (row, column) order with origin bottom-left. Default is an empty list.
Examples
library(dplyr)
library(sf)
pts <- london_boroughs |> st_drop_geometry() |> select(area_name, x = easting, y = northing)
solution <- points_to_grid(pts, n_row = 8, n_col = 8, spacers = list(), compactness = .6)
solution
#> row col area_name
#> 1 5 5 City of London
#> 2 6 7 Barking and Dagenham
#> 3 7 3 Barnet
#> 4 4 7 Bexley
#> 5 6 3 Brent
#> 6 2 6 Bromley
#> 7 5 3 Camden
#> 8 2 5 Croydon
#> 9 5 2 Ealing
#> 10 8 5 Enfield
#> 11 4 6 Greenwich
#> 12 6 5 Hackney
#> 13 4 3 Hammersmith and Fulham
#> 14 7 4 Haringey
#> 15 6 2 Harrow
#> 16 6 8 Havering
#> 17 5 1 Hillingdon
#> 18 4 2 Hounslow
#> 19 6 4 Islington
#> 20 4 4 Kensington and Chelsea
#> 21 2 3 Kingston upon Thames
#> 22 3 5 Lambeth
#> 23 3 6 Lewisham
#> 24 2 4 Merton
#> 25 6 6 Newham
#> 26 7 6 Redbridge
#> 27 3 3 Richmond upon Thames
#> 28 4 5 Southwark
#> 29 1 4 Sutton
#> 30 5 6 Tower Hamlets
#> 31 7 5 Waltham Forest
#> 32 3 4 Wandsworth
#> 33 5 4 Westminster