R: number of adjacent/neighbour cells in raster

Solution 1:

Using adjacent-function in a self-defined function

I've defined a simple example raster and used a simple condition to define land cells and water cells (this should be adjusted according to your data):

rasterExample <- raster(matrix(runif(100, 0, 1),10,10))

getNumbersOfLandcells <- function(raster2analyze) {
  raster2return <- raster2analyze
  
  #get 0 for no land and 1 for land - this should be adjusted!
  raster2analyze[raster2analyze < 0.5] <- 0
  raster2analyze[raster2analyze >= 0.5] <- 1
  
  Landcells <- which(values(raster2analyze) == 1)
  
  for (cell in Landcells){
    #count cells with 1 
    ncells <- adjacent(raster2analyze, cell=cell, direction=8,include=F,pairs=F)
    nLand <- sum(raster2analyze[ncells], na.rm=T)
    
    raster2return[cell] <- nLand
  }
  
  return(raster2return)
}

rasterLandcells <- getNumbersOfLandcells(rasterExample)