Count shapefile length (line) in each polygon of another shapefile (grid)

51 Views Asked by At

I am trying to quantify the length of a road network, on each cell of a lattice grid. Both my road network and my lattice grid are shapefiles, a polyline and a polygon respectively.

I would like to process them on the "sf" package in R, however I found no command for computing the total length of the road network in each cell of the grid. Do you have any idea on how this could be implemented?

Best,

Jacopo Cerri

1

There are 1 best solutions below

0
jamespryor On

From the limited information required, it sounds like you need to perform an intersection of the lines (road network) with the grid, and calculate the length of said intersection(s) per cell:

library(tidyverse)
library(sf)

########### create indicative cell grid ##########

# define individual cells:
cell_1 <- 'POLYGON((0 0, 0 2, 2 2, 2 0, 0 0))'
cell_2 <- 'POLYGON((0 2, 0 4, 2 4, 2 2, 0 2))'
cell_3 <- 'POLYGON((2 0, 2 2, 4 2, 4 0, 2 0))'
cell_4 <- 'POLYGON((2 2, 2 4, 4 4, 4 2, 2 2))'

cells <- c(cell_1, cell_2, cell_3, cell_4)

# create SimpleFeatures:
cells <- tibble(id = c('A', 'B', 'C', 'D'),
                geometry = cells) %>%
  st_as_sf(wkt = 'geometry')

######### create indicative line network #########

line_1 <- 'LINESTRING(1 1, 1 3, 3 3)'
line_2 <- 'LINESTRING(3.5 3, 3.5 1)'

lines <- c(line_1, line_2)

lines <- tibble(id = c('Y', 'Z'),
                geometry = lines) %>%
st_as_sf(wkt = 'geometry')

####### perform intersection & length calc. ######

lengths <- cells %>%
  st_intersection(lines) %>%
  mutate(length = st_length(.)) %>%
  group_by(id) %>%
  summarise(length = sum(length)) %>% # sum length per grid cell
  st_drop_geometry()

# optional...
cells <- cells %>%
  left_join(lengths, by = 'id') %>%
  relocate(geometry, .after = last_col())