Reputation: 91
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!
Upvotes: 1
Views: 811
Reputation: 31452
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,])
For convenience, you can convert this list into a raster stack
st = stack(dp)
plot(st)
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.
Upvotes: 5