Search code examples
rgisshapefiler-sf

Clip a grid to a shapefile but keep cells whole


I have two shapefiles: One Hexagonal Grid, One Bounding Shapefile:

Grid & Bounding Shapefile

I am trying to clip the Grid to the Shapefile BUT no matter how I try st_intersect(), st_overlap(), st_contains(), etc, the result is always the same:

Undesired Clipping Output

What I want is to clip the Grid and keep the remaining cells whole like this:

Desired Clipping Output

I can accomplish this in QGIS, but I am looking for a solution in R. Thanks!


Solution

  • Here's one way:

    library(sf)
    library(tidyverse)
    
    
    # example data
    # using the state border of north carolina
    nc = st_read(system.file("shape/nc.shp", package="sf")) %>%
      st_union()
    
    # create a bounding box
    bbox <- st_bbox(nc) %>% st_as_sfc()
    
    # make a hexagonal grid over the bounding box
    hex_grid <- st_make_grid(bbox, square = FALSE, n = 40)  
    hex_sf <- hex_grid %>% st_as_sf()
    
    #index of hexagons fully or partially covered by the state
    intersections_index <- st_intersects(nc, hex_grid, sparse = F)
    
    # sf object of only the hexagons we want
    intersected_hex <- hex_sf[intersections_index, ]
    
    ## plotting it all:
    ggplot() + 
      geom_sf(data = hex_sf, color = 'orange') +
      geom_sf(data = intersected_hex, fill = 'gray40')+
      geom_sf(data = nc, color = 'blue', fill = NA) 
    

    Full hexagonal grid in orange, selected hexagons in gray, state outline (bounding shapefile) in blue.

    Created on 2023-01-18 by the reprex package (v2.0.1)