5

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?

9

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)

enter image description here

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 – Splash1199 Feb 6 '17 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. – Spacedman Feb 6 '17 at 18:37
  • is there an sf solution to this...? – B. Davis Feb 22 at 20:18
  • @B.Davis convert the sf features to sp, use this? – Spacedman Feb 22 at 23:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.