# How to increase the number of the adjacent cells of a focal cell?

I want to recover the adjacent cells around a focal cell, I could do it by using the function `adjacent` form the package « raster »,

`cells_adj <- adjacent(Habitat[[1]], cells=cells_xy, directions=neigh[nei], pairs=FALSE)`

where `neigh <- c(4,8, 16)` this function gives 4,8 or 16 cells through the argument `directions`, I want to include more cells (24, 48, 80, 120, and 168). Is there any option to do that?

``````directions: the number of directions in which cells should be
connected: 4 (rook's case), 8 (queen's case), 16 (knight and
one-cell queen moves), or 'bishop' to connect cells with
one-cell diagonal moves. **Or a neighborhood matrix (see
Details)**

Details:

A neighborhood matrix identifies the cells around each cell that
are considered adjacent. The matrix should have one, and only one,
cell with value 0 (the focal cell); at least one cell with value 1
(the adjacent cell(s)); All other cells are not considered
``````

So the "queen's adjacency" is `directions=8` or a 3x3 matrix of 1s with a 0 in the middle. We can test that:

Make a sample raster:

``````> Habitat = raster()
> Habitat[]=1:ncell(Habitat)
``````

``````> adjacent(Habitat, cells=c(1,100,200), directions=8)
from  to
[1,]    1 360
[2,]  100  99
[3,]  200 199
[4,]    1 720
[5,]  100 459
[6,]  200 559
[7,]    1   2
[8,]  100 101
[9,]  200 201
[10,]    1 362
[11,]  100 461
[12,]  200 561
[13,]    1 361
[14,]  100 460
[15,]  200 560
``````

make a 3x3 matrix with a zero in the middle:

``````> m8 = matrix(1, ncol=3, nrow=3)
> m8[2,2]=0
``````

Do the adjacency with that matrix:

``````> adjacent(Habitat, cells=c(1,100,200), directions=m8)
from  to
[1,]    1 360
[2,]    1 720
[3,]    1 361
[4,]    1   2
[5,]    1 362
[6,]  100  99
[7,]  100 459
[8,]  100 460
[9,]  100 101
[10,]  100 461
[11,]  200 199
[12,]  200 559
[13,]  200 560
[14,]  200 201
[15,]  200 561
``````

by inspection, or by sorting the outputs in the same order, you'll see these are the same.

So to do the "24" neighbour adjacency you need a 5x5 matrix of 1s with a zero in the middle:

``````> m24 = matrix(1, ncol=5, nrow=5)
> m24[3,3]=0
> m24
[,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    1    1    1    1    1
[3,]    1    1    0    1    1
[4,]    1    1    1    1    1
[5,]    1    1    1    1    1
``````

then do, for example a single cell:

``````> a24 = adjacent(Habitat, cells=c(32000), directions=m24)
``````

which we can confirm returns 24 adjacent cells:

``````> table(a24[,1])
32000
24
``````

For an edge or corner cell, you get fewer:

``````> a24 = adjacent(Habitat, cells=c(1), directions=m24)
> table(a24[,1])

1
14
``````