I have some line features (eg. 1000 meter isobath), and I would like to make a raster file for my study area where the value of each cell is the distance to the line feature. Any idea what function I would use in R to accomplish this?
For some SpatialLines object
Sl and some raster
r compute distances from each feature in
Sl to the raster points with:
require(rgeos) dd = gDistance(Sl, as(r,"SpatialPoints"), byid=TRUE)
This creates a matrix with a column for each feature in
Sl. To get the nearest distance to any feature, apply
min over rows:
r = apply(dd,1,min) plot(r)
To reproduce this, create
Sl as per the example in
class?SpatialLines and create
r = raster(extent(Sl)). Adjust the raster creation with whatever resolution and extent you really need.
If you have a lot of line features then you might want to merge them into one feature so that the return from
gDistance isn't a huge matrix. You can do that with