Subset sf object into multiple sf objects based on adjacency

Viewed 419

I have a sf object as in the example here:

library(sf)
fname <- system.file("shape/nc.shp", package="sf")
nc <- st_read(fname)
plot(nc[1])

Created on 2021-04-15 by the reprex package (v2.0.0)

I want to subset my data in such a way that I could get the approximate four different sf objects for four different quadrants. For the data which I am working now, subset method like this nc[1:50, ] doesn't make sense since the rows are randomly ordered. And doing so will reduce the number of features but not the extent. I even tried group_by(geom), didn't work for me.

Can you help me here with this part using nc data as example?

1 Answers

I suggest you assign your objects to quadrants via sf::st_join().

It has a very helpful argument largest which ensures that the small polygons are not multiplied (but assigned to the quadrant to which falls the largest area of the small polygon). So NC keeps all 100 counties / and no duplicites are created.

To create the quadrants object consider applying sf::st_make_grid() to the bounding box of your spatial object, specifying that you want two by two split.

For a full workflow consider the following code:

library(sf)
fname <- system.file("shape/nc.shp", package="sf")
nc <- st_read(fname)
plot(nc[1])

# create quadrants 
quads <- st_bbox(nc) %>% 
  st_make_grid(n = 2) %>% 
  st_as_sf(crs = st_crs(nc)) %>% 
  dplyr::mutate(quad_id = 1:4)

# a visual check
plot(st_geometry(nc))
plot(st_geometry(quads), add = T)

nc with quadrants shown

# intersect NC by the quadrants
nc_intersected <- st_join(nc, 
                          quads,
                          largest = T) # do *not* multiply polygons!

# a visual check
plot(nc_intersected["quad_id"])

nc counties by quadrant

Related