terra icon indicating copy to clipboard operation
terra copied to clipboard

distance function: allow return of raster values as well as distances

Open SimonDedman opened this issue 2 years ago • 1 comments

Per this thread and the comments on the answer, it would be great to be able to specify if you also want to return the values of the nearest pixels in the target raster, rather than just the distance to those pixels.

Indeed in my current case, IDK that I need the distance at all, I just need points which are within 200m of the raster to get the nearest raster pixel's value appended - I don't subsequently care how far the donor pixel was (so long as it was <200m).

Not sure whether this would be a staggering amount of work, or conversely, once the code is at the point of having calculated the nearest pixel, it'd simply be a case of using that index to grab the required value(s).

Cheers for considering this regardless.

SimonDedman avatar Jul 23 '23 20:07 SimonDedman

That would be a life savoir... Are there any plans to implement something along these lines?

ratnanil avatar Jul 03 '24 14:07 ratnanil

I am sorry that it took me so long, but here is a first attempt:

library(terra)
r <- rast(ncols=40, nrows=40, crs="+proj=utm +zone=1 +datum=WGS84")
r[4, 5:15] <- 5:15
r[36, 25:35] <- 25:35
d <- distance(r, values=TRUE)
plot(d)

Image

And

library(terra)
r <- rast(ncols=40, nrows=40, crs="lonlat")
r[4, 5:15] <- 5:15
r[36, 25:35] <- 25:35
d <- distance(r, values=TRUE)
plot(d)

Image

rhijmans avatar Jan 25 '25 19:01 rhijmans