# NOT RUN {
library(scapesClassification)
library(terra)
## CREATE A DUMMY RASTER AND COMPUTE ATTRIBUTE TABLE ##
r <- terra::rast(matrix(c(NA,100,100,NA,100,100,0,0,0),
nrow = 3,
ncol = 3,
byrow = TRUE))
at <- attTbl(r, var_names = c("dummy_var"))
## RASTER CELL NUMBERS ##
rcn <- r; rcn[] <- 1:9
## PLOT DATA AND CELL NUMBERS ##
oldpar <- par(mfrow = c(1,2))
m <- c(4, 1, 4, 1)
plot(r, col="grey90", colNA="red3", mar=m, asp=NA, axes=FALSE, legend=FALSE)
text(r)
lines(r)
mtext(side=3, line=0.2, adj=0, cex=1.5, font=2, "Dummy_var")
legend("bottomright", ncol = 1, bg = "white", fill = c("red3"),
legend = c("NA cells (1 and 4)"))
plot(rcn, col="grey90", mar=m, asp = NA, axes=FALSE, legend=FALSE)
text(rcn)
lines(rcn)
mtext(side=3, line=0.2, adj=0, cex=1.5, font=2, "Cell numbers")
par(oldpar)
## NEIGHBORHOODS - CELL NUMBERS ##
# Cells 1 and 4 are omitted because they are NAs
nbs_CELL <- ngbList(r, rNumb = FALSE)
nbs_CELL
## NEIGHBORHOODS - ROW NUMBERS ##
# Cells 1 and 4 are omitted because they are NAs
nbs_ROW <- ngbList(r, rNumb = TRUE, attTbl = at)
nbs_ROW
# Numbers in 'nbs_ROW' refer to row numbers
# (e.g. number 1 refers to the cell #2)
at$Cell[1]
# (e.g. number 2 refers to the cell #3)
at$Cell[2]
# (e.g. number 5 refers to the cell #7)
at$Cell[5]
## CONSIDER THE NEIGHBORHOOD OF CELL #2 ##
# Cell #2 corresponds to the 1st element of both 'nbs_CELL' and 'nbs_ROW'
# because raster cell 1 is an NA-cell
r[1]
# Neighborhood cell #2 corresponds to cells:
nbs_CELL[1]
# Neighborhood cell #2 corresponds to rows:
nbs_ROW[1]
# Rows can be converted to cell numbers
at$Cell[ nbs_ROW[[1]] ]
# Note that 'at$Cell[ nbs_ROW[[1]] ]' is not equal to 'nbs_CELL'
identical( at$Cell[ nbs_ROW[[1]] ] , nbs_CELL[[1]] )
# This is because raster cells 1 and 4 (NA-cells) are omitted in 'nbs_ROW'
setdiff(nbs_CELL[[1]], at$Cell[ nbs_ROW[[1]] ])
r[c(1,4)]
# }
Run the code above in your browser using DataLab