Trying to summarize line lengths within grid cells in R

Viewed 386

I am trying to calculate the sum of line lengths within grid cells in R. I have been using this as a reference https://gis.stackexchange.com/questions/289350/calculate-sum-of-line-lengths-in-r

The problem I am having is that when I create a grid using st_make_grid, there is no ID column for when I match the line intersection lengths to the grid. I have tried using as.Spatial to convert the grid to a SpatialPolygonsDataFrame so that I can add columns, but then st_length and st_intersections won't work because the grid is no longer an "sf" object. What would be the best workaround to this?

1 Answers

You need to convert the grid from sfc to sf object via a sf::st_as_sf()

Consider this example, built on the well known & much loved nc.shp dataset that ships with {sf}

library(sf)
library(dplyr)

shape <- st_read(system.file("shape/nc.shp", package="sf")) %>%  
  summarise() %>% 
  st_geometry() %>% 
  st_cast("POLYGON") %>% 
  st_cast("LINESTRING")

# a line around North Carolina - to get a line object
plot(shape)

enter image description here

grid <- st_make_grid(x = st_bbox(shape),
                     n = c(30, 10)) %>% 
  st_as_sf() %>% # this is the part!
  mutate(id = 1:nrow(.)) # now tis possible to add a row id

intersection <- st_intersection(grid, shape) %>% 
  mutate(lenght = st_length(.)) %>% 
  st_drop_geometry() # complicates things in joins later on


grid <- grid %>% 
  left_join(intersection, by = "id")

plot(grid["lenght"])

enter image description here

Related