title: Calculate line density within a buffer from a raster
body: <p>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 <code>rasterToContour</code> <code>(package raster)</code>. Then, I'm thinking of calculating total length of lines within the buffer (in km) and the buffer area (in km²).</p>
  
  <pre><code>r &lt;- raster(rast_path)
  x &lt;- rasterToContour(r)
  </code></pre>
  
  <p>Here is a reproducible example:</p>
  
  <pre><code>## To create raster:
  library(raster)
  library(rgeos)
  r &lt;- raster(ncols=90, nrows=50)
  values(r) &lt;- sample(1:10, ncell(r), replace=TRUE)
  
  ## Road raster
  r[r[] &lt; 10] &lt;- 0
  r[r[] &gt;= 10] &lt;- 1
  plot(r)
  
  ## To create spatial lines 
  line1 &lt;- rbind(c(-125,0), c(0,60))
  line2 &lt;- rbind(c(0,60), c(40,5))
  line3 &lt;- rbind(c(40,5), c(15,-45))
  line1_sp &lt;- spLines(line1)
  line2_sp &lt;- spLines(line2)
  line3_sp &lt;- spLines(line3)
  
  ## To create buffer around lines
  line2_buff &lt;- gBuffer(line2_sp, width=20)
  plot(line2_sp,add=T)
  plot(line2_buff,add=T)
  </code></pre>