rdistancerasterterra

Distance only to Non-NA cells in Terra raster


I have a SpatRaster where cells are either NA or 1. There are some points on it.

r <- rast(ncols=36, nrows=18, crs="+proj=longlat +datum=WGS84")
r[1:200] <- 1
plot(r)

p2 <- vect(rbind(c(30,-30), c(25,40), c(-9,-3)), crs="+proj=longlat +datum=WGS84")
plot(p2, add = T)

enter image description here

Is there a way to calculate the distance of only the non-NA cells to the points? I'm trying to reduce computation when calculating distances on a very large raster that is mostly NAs.

I tried the following:

dist<- distance(x = not.na(r), y = p2)
plot(dist)

enter image description here

This is my desired result: enter image description here


Solution

  • You could achieve what you are asking with the exclude parameter of distance if you use a single raster. To do that, you would set the cells that overlap the target points to a value different from the rest of the raster:

    library(terra)
    # create dataset
    r <- rast(ncols=36, nrows=18, crs="+proj=longlat +datum=WGS84")
    r[1:200] <- 1
    p2 <- vect(rbind(c(30,-30), c(25,40), c(-9,-3)), crs="+proj=longlat +datum=WGS84")
    
    # set values of cells overlapping points to -1
    r[cells(r,p2)[,2]] <- -1
    dist <- distance(x = r, target = 1, exclude= NA)
    plot(dist)
    

    enter image description here

    However, after some benchmarking with @L Tyrone (see his excellent answer and our discussion), it turns out that a simple:

    dist <- distance(r, p2)
    dist <- mask(dist, r)
    

    is computationally faster.