Search code examples
rterra

Linking focal cell ids with adjacent cell ids using terra in R


I have a large raster and I need to link the ids of each of the focal cells with the ids of each focal's adjacent cell (in my case 'queen' neighbours), as shown below

finding raster neighbours, including the id of the focal cell

In my case, each focal cell is a 5km square representing use by an animal, and each neighbouring cell represents an available domain for that location (but the focal cell is also available and must be included). Within this larger 5km grid I am extracting covariates at 30 m resolution for each of those 5km squares. I hope that makes sense!

I tried this solution: (Get values from adjacent cells raster R)

But, while close to what I need, it doesn't produce the data in a one-to-many format that I think I need.

Here is my code to generate an example raster, and generate those adjacent cells, but I'm just not sure how to link the id of each of the adjacents to the id of the focal. Importantly, the focal must also be considered as part of the available domain, thus an adjacent.

create example raster

library(terra)
d = rast(nrow = 5, ncol = 5)
values(d) <- 1:ncell(d)
#select some cell ids to test
cell_ids = c(3, 14, 22)

#I'm not sure this next line is required
dvec = as.data.frame(d)
colnames(dvec) = "focal_id"

run terra::adjacent

dadj = as.vector(terra::adjacent(d, cells = cell_ids, include = TRUE, directions = "queen"))

#cell id vec to
cell.rep = rep(c(3,14,22),each=9)

#and this is not correct
df = as.data.frame(cbind(cell.rep, dadj))

What I want is an output as such: formatted output I'm after

#EDIT: I just found that:

cell.rep = rep(c(3,14,22),each=9)


dadj = c()
for(i in cell_ids){
   adel = as.vector(terra::adjacent(d, cells = i, include = TRUE,
   directions = "queen"))
   dadj = c(dadj, adel)
}

df = as.data.frame(cbind(cell.rep, dadj))

Produces what I'm after, but is there a faster way?


Solution

  • You can do this in one call to terra::adjacent with argument "pairs=TRUE"

    # example data 
    library(terra)
    d <- rast(nrow = 5, ncol = 5)
    cell_ids <- c(3, 14, 22)
    
    # solution
    da <- adjacent(d, cell_ids, directions="queen", pairs=TRUE, include=TRUE)
    
    head(da)
    #    from to
    #[1,]    3  3
    #[2,]    3  2
    #[3,]    3  4
    #[4,]    3  7
    #[5,]    3  8
    #[6,]    3  9