r - Calculate line density within a buffer from a raster -


is there way calculate road density (km/km²) within buffer around spatial lines? roads represented pixels (1 pixel = 625 m²) in raster. began convert road pixels polylines using function rastertocontour (package raster). then, i'm thinking of calculating total length of lines within buffer (in km) , buffer area (in km²).

r <- raster(rast_path) x <- rastertocontour(r) 

here reproducible example:

## 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)  ## 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)  ## create buffer around lines line2_buff <- gbuffer(line2_sp, width=20) plot(line2_sp,add=t) plot(line2_buff,add=t) 

you're looking road length (kilometers) divided buffer area (square kilometers), right? calculate road length, can use method rastertocontour(), although isn't reproducible example provided.

but calculate area of buffer in square kilometers, can do: n <- length(extract(r, line2_buff)) n number of pixels in buffer, 625 m^2 each. conversion factor need 1 km^2 = 1,000,000 m^2. together, area of buffer in km^2 given by:

length(extract(r, line2_buff)) * 625 / 1000000 

Comments