Search code examples
raster

Raster::focal function replaces edge cells with NA values


I am trying to use raster::focal to find out how many neighbors of value 1 each raster cell has. However, I have noticed that in the resulting raster the edge cells have been replaced with NA values. How can I get neighbor counts for the outer edge of the raster?

Here is a reproducible example:

#create raster and add 1's and 0's
land <- raster(matrix(0, 8, 10), xmn=408027.5, xmx=413027.5, ymn=4370000, 
ymx=4374000)
land[4:8, 2:5] <- 1
land[2:3, 8:9] <- 1
land[1,0:10] <- 1
land[is.na(land[])] <- 0
#plot the raster
plot(land)

raster

#create window for focal function
w <- matrix(1,3,3)
#run raster::focal
land.foc <- focal(land, w=w, fun=sum)
#plot resulting focal raster
plot(land.foc)

focal

#plot NA values in land.foc
plot(is.na(land.foc))

edge NAs

However, as you can see when you compare the two rasters, the outer-most cells in the focal raster have been replaced with NA's.


Solution

  • You just need to set pad=TRUE and padValue=0. This 'extends' your raster and adds virtual rows and columns with you padValue, in this case 0.

    land.foc <- focal(land, w=w, fun=sum,pad=T,padValue=0)
    
    plot(land.foc)
    

    enter image description here

    plot(is.na(land.foc))
    

    enter image description here

    Edit:

    Another way of looking at it is that the virtual cells don't have any values, they are NA.

    So instead of assigning 0 as padValue, just add na.rm=TRUE to your call.

    If you really need to do something else with the virtual cells, you can create your own function, which handles the NA cells more specific, that you then pass into focal.