1

I'm trying to use distanceFromPoints function in raster package as:

distanceFromPoints(object,xy,...)

Where, object is raster and xy is matrix of x and y coordinates

Now, if my raster has, for example, 1000 cells and xy represents one point, I get 1000 values representing distances between xy and each raster cell. my problem is when xy has multiple coordinates, e.g., 10 points. the function description indicates that xy can be multiple points but when I run this function with multiple XY points, I still get only 1000 values while I'm expecting 1000 values for each coordinate in XY. How does this work?

Thanks!

Cyrus Mohammadian
  • 4,982
  • 6
  • 33
  • 62
Amir M.
  • 71
  • 7

1 Answers1

5

using distanceFromPoints on multiple points gives a single value for each raster cell, which is the distance to the nearest point to that cell.

To create raster layers giving the distance to each point separately, you can use apply

a reproducible example:

r = raster(matrix(nrow = 10, ncol = 10))
p = data.frame(x=runif(5), y=runif(5))
dp = apply(p, 1, function(p) distanceFromPoints(r,p))

This gives a list of raster layers, each having the distance to one point

# for example, 1st raster in the list has the distance to the 1st point
plot(dp[[1]])
points(p[1,])

enter image description here

For convenience, you can convert this list into a raster stack

st = stack(dp)
plot(st)

enter image description here

A final word of caution:

It should be noted that the raster objects thus created do not really contain any more information than the list of points from which they are generated. As such, they are a computationally- and memory-expensive way to store that information. I can't easily think of any situation in which this would be a sensible way to solve a specific question. Therefore, it may be worth thinking again about the reasons you want these raster layers, and asking whether there may be a more efficient way to solve you overall problem.

dww
  • 30,425
  • 5
  • 68
  • 111
  • Thank you so much. I was trying not to use apply or any loop because there are thousands of points that I'm dealing with and this turns into a time consuming calculation in my code. But as you pointed out, this seems to be the only option. Thank you so much for the response. – Amir M. Dec 28 '16 at 15:06
  • Glad it helped. If this was useful and answered your question, please consider upvoting by clicking on the up arrow, and accepting answer by clicking on the tick (check) mark. This is the preferenced way to say thanks in SO, rather than in comments. – dww Dec 28 '16 at 15:26