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 1


For some SpatialLines object Sl and some raster r compute distances from each feature in Sl to the raster points with:

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)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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