| adjacency | R Documentation |
Find neighbouring cells by index, using only the grid dimension.
adjacency(dimension, cell, directions = "queen")
dimension |
integer vector of ncol, nrow |
cell |
integer vector of cell indices (1-based) |
directions |
character, one of |
Given cell indices into a grid of known dimension, return the indices of
neighbouring cells. Out-of-bounds neighbours (at grid edges) are NA.
The directions argument controls which neighbours are returned:
"queen" (default): all 8 neighbours (rook + bishop)
"rook": 4 cardinal neighbours (up, down, left, right)
"bishop": 4 diagonal neighbours
Column order for "queen" is: up, down, left, right, upleft, upright,
downleft, downright. For "rook": up, down, left, right. For "bishop":
upleft, upright, downleft, downright. Direction names refer to the
raster convention where cell 1 is at the top-left.
integer matrix with one row per cell and one column per neighbour
direction. Column names indicate the direction. Out-of-bounds neighbours
are NA.
A key use case is converting area-based cell values to corner vertex values for mesh generation. Each corner vertex is shared by up to four cells. For example, the top-left corner of a cell is shared with the cell above, the cell to the left, and the cell diagonally above-left:
upleft | up --------x------ vertex 'x' = mean of upleft, up, left, self left | self
The queen-connected neighbours give all the cells needed to compute every corner vertex. Averaging the appropriate neighbours provides weighted corner values from flat pixel areas, which is the basis for constructing continuous meshes from raster data (as used by quadmesh and anglr).
## 4x3 grid (4 columns, 3 rows), 12 cells
adjacency(c(4, 3), cell = 6)
adjacency(c(4, 3), cell = 6, directions = "rook")
adjacency(c(4, 3), cell = 6, directions = "bishop")
## corner cell has fewer valid neighbours
adjacency(c(4, 3), cell = 1)
## multiple cells at once
adjacency(c(4, 3), cell = 1:12)
## ------------------------------------------------
## Corner vertex interpolation from area values
## ------------------------------------------------
dm <- c(4, 3)
elev <- c(10, 12, 14, 16, 11, 13, 15, 17, 10, 11, 13, 14)
## The top-left corner of each cell is shared by self, the
## cell above, the cell to the left, and the cell diagonally
## above-left. Average these for the vertex value:
nb <- adjacency(dm, seq_along(elev))
vals <- cbind(elev, elev[nb[, "up"]],
elev[nb[, "left"]], elev[nb[, "upleft"]])
corner <- rowMeans(vals, na.rm = TRUE)
matrix(corner, nrow = 3, byrow = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.