Is there a way to calculate road density (km/km²) within a buffer around spatial lines? The roads are represented by pixels (1 pixel = 625 m²) in a raster. So I began to convert the road pixels into polylines by using the function rasterToContour
(package raster)
. Then, I'm thinking of calculating total length of lines within the buffer (in km) and the buffer area (in km²).
r <- raster(rast_path)
x <- rasterToContour(r)
Here is a reproducible example:
## To create raster:
library(raster)
library(rgeos)
r <- raster(ncols=90, nrows=50)
values(r) <- sample(1:10, ncell(r), replace=TRUE)
## Road raster
r[r[] < 10] <- 0
r[r[] >= 10] <- 1
plot(r)
## To create spatial lines
line1 <- rbind(c(-125,0), c(0,60))
line2 <- rbind(c(0,60), c(40,5))
line3 <- rbind(c(40,5), c(15,-45))
line1_sp <- spLines(line1)
line2_sp <- spLines(line2)
line3_sp <- spLines(line3)
## To create buffer around lines
line2_buff <- gBuffer(line2_sp, width=20)
plot(line2_sp,add=T)
plot(line2_buff,add=T)