Search code examples
rdistancerasterspatialterra

R - terra::distance() equivalent of raster::gridDistance(..., origin = x, omit = y)


UPDATE - this question relates to terra 1.4-1, and is now obsolete with terra 1.5-12 (or earlier?).


I am looking for the terra equivalent of raster::gridDistance(..., origin = my_origin, omit = my_omit).

I found what looks to be an old webpage on terra::gridDistance, from terra v0.2-8 here, but from what I can gather terra::distance is the current replacement for raster::gridDistance (list of terra's replacement functions here).

However, I don't know to implement omit = my_omit (or equivalent) in terra::distance. From the documentation page it looks like any non-NA is deemed the origin, but there is no reference to omit, or the option to change the origin to a specific value (unlike the raster::gridDistance example below).

This is the example from raster::gridDistance:

library(raster)

# world lon/lat raster
r <- raster(ncol=10,nrow=10, vals=1)
r[48] <- 2     # this will be the origin
r[66:68] <- 3  # this will be the area that can't be traversed
plot(r)

d <- gridDistance(r,origin=2,omit=3) 
plot(d)

enter image description here

Can anyone reproduce this example using terra::distance?

I can do what I need to do using raster, but I'm still learning how to handle spatial raster data properly and am making an effort to learn the new terra package.


Solution

  • Thanks to @lovalery for pointing this out in the comments.

    In the original question I was using terra 1.4-1. As of January 2022, terra 1.5-12 has been released (Jan 13th 2022), and it now includes a terra::gridDistance() function which is very similar to the raster::gridDistance() function.

    For the sake of completeness, this is the example from ?terra::gridDistance:

    #world lon/lat raster
    r <- rast(ncol=10,nrow=10, vals=1)
    r[48] <- 2
    r[66:68] <- 3
    d <- gridDistance(r,origin=2,omit=3) 
    plot(d)
    
    #UTM small area
    crs(r) <- "+proj=utm +zone=15 +ellps=GRS80 +datum=NAD83 +units=m +no_defs"
    d <- gridDistance(r,origin=2,omit=3) 
    plot(d)
    

    enter image description here