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?
1 Answer
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
as 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 gUnion(Sl, Sl)
.
-
I got the following erroer: error in r[]=apply(dd, 1, min); dim(x) must have a positive length Commented Feb 6, 2017 at 17:23
-
Is that with your data or the exact example I've given? Because if its your data then your
dd
object isn't what it should be and only you can investigate that unless you give us your data. Commented Feb 6, 2017 at 18:37 -
-