Provides R bindings for H3, a hexagonal hierarchical spatial indexing system.

Documentation

Notes

Succesfully built on

  • Linux
  • OSX
  • Windows

Since v3.7.1 {h3} comes with a bundled version of the H3 C library, so that you no longer have to build it yourself before installing the R package.

Installation

You can install h3 from github with:

# install.packages("remotes")
remotes::install_github("crazycapivara/h3-r")

Usage

Core functions:

library(h3)

coords <- c(37.3615593, -122.0553238)
resolution <- 7

# Convert a lat/lng point to a hexagon index at resolution 7
(h3_index <- geo_to_h3(coords, resolution)) 
#> [1] "87283472bffffff"

# Get the center of the hexagon
h3_to_geo_sf(h3_index)
#> Simple feature collection with 1 feature and 0 fields
#> geometry type:  POINT
#> dimension:      XY
#> bbox:           xmin: -122.0503 ymin: 37.35172 xmax: -122.0503 ymax: 37.35172
#> CRS:            EPSG:4326
#>                     geometry
#> 1 POINT (-122.0503 37.35172)

# Get the vertices of the hexagon
h3_to_geo_boundary(h3_index)
#> [[1]]
#>           lat       lng
#> [1,] 37.34110 -122.0416
#> [2,] 37.35290 -122.0340
#> [3,] 37.36352 -122.0428
#> [4,] 37.36234 -122.0591
#> [5,] 37.35054 -122.0666
#> [6,] 37.33992 -122.0579

# Get the polygon of the hexagon
h3_to_geo_boundary_sf(h3_index)
#> Simple feature collection with 1 feature and 0 fields
#> geometry type:  POLYGON
#> dimension:      XY
#> bbox:           xmin: -122.0666 ymin: 37.33992 xmax: -122.034 ymax: 37.36352
#> CRS:            EPSG:4326
#>                         geometry
#> 1 POLYGON ((-122.0416 37.3411...

Useful algorithms:

# Get all neighbors within 1 step of the hexagon
radius <- 1
(neighbors <- k_ring(h3_index, radius))
#> [1] "87283472bffffff" "87283472affffff" "87283470cffffff" "87283470dffffff"
#> [5] "872834776ffffff" "872834729ffffff" "872834728ffffff"

h3_to_geo_boundary_sf(neighbors) %>%
  sf::st_geometry() %>% plot(col = "blue")


h3_set_to_multi_polygon(neighbors) %>%
  sf::st_geometry() %>% plot(col = "green")

Run tests

devtools::test(reporter = "minimal")
#> Loading h3
#> Testing h3
#> ..............................................