Search code examples
rrasterneighbours

R: number of adjacent/neighbour cells in raster


I have a raster grid of Chile and want to compute the number of terrestrial cells in the neighbourhood. Is there a way in R to compute the number of adjacent/neighbour cells in a raster? So most cells should get the value 8 (due to 8 surounding cells), but cells along coast will get less.


Solution

  • 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)