rspatialgeoh3

Convert Shapefile to H3 - R


I have a gpkg file which contains some buildings and am looking to convert this to H3 size 11.

BUILDINGS <- st_read(GPKG, layer = "buildings")

Basically anywhere one of these buildings is located gets a hexagon, and where there aren't any buildings there is no hexagon.

I tried using some packages i.e. "h3jsr" and "h3"

and also tried

install.packages("remotes")
remotes::install_github("crazycapivara/h3forr")

hoping to use the "geo_to_h3" function, but it just says it cannot find the function at all so not sure whats happening there.

Any help would be greatly appreciated!

Update

So not each individual building is a polygon but a collection of buildings are grouped into one polygon.


Solution

  • Found the answer - Some buildings did not cross the centre point of the H3 cells at size 11, which caused an error. This was fixed by reducing the size of the cells and then finding the parent cells.

    FINAL_CELLS <- data.frame()
    for(i in 1:nrow(BUILDING)){
      # Subset each Polygon
      SUB_BUILDING <- st_transform(BUILDING[i,], crs = 4326)
      
      # Convert polygon to H3 cells (must be higher resolution to avoid issues)
      CELLS <- polygon_to_cells(SUB_BUILDING, res = 14, simple = FALSE)
      
      # Get parent H3 cells from child H3 cells (This is final resolution)
      P <- get_parent(unlist(CELLS$h3_addresses), res = 11, simple = T)
      
      # Remove duplicate H3 cells
      P <- data.frame(id = SUB_BUILDING$id, cell =  unique(P))
      
      FINAL_CELLS <- rbind(P,FINAL_CELLS)
      
      print(paste(i,"-",Sys.time()))
    }