R:栅格中的 adjacent/neighbour 个像元数

R: number of adjacent/neighbour cells in raster

我有一个智利的栅格网格,想计算智利的陆地细胞数量 附近。 R 中有没有一种方法可以计算栅格中 adjacent/neighbour 像元的数量?所以大多数单元格应该得到值 8(由于周围有 8 个单元格),但沿海单元格会得到更少。

在 self-defined 函数中使用 adjacent-function

我已经定义了一个简单的示例栅格并使用了一个简单的条件来定义陆地像元和水像元(这应该根据您的数据进行调整):

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)