Search code examples
rmatrixgisrasterr-raster

How to aggregate a binary raster into percentage in R


I have a binary raster(r) at 1 meter resolution and I want to convert it into a percentage value at 4m resolution.This new raster would have each pixel value representing the percent, calculated on basis of total frequency of 1 out of 16 pixels.I looked at the raster package which has aggregate function. However, this doesn't work.

   newras <-aggregate(r, fact=4,  fun= percent)

Solution

  • What you do does not work because there is no function called percentage. But you can make one. In this case, the mean value is the fraction, so you multiply that with 100 to get the percentage.

    Example data

    library(raster)
    r <- raster()
    set.seed(0)
    values(r) <- sample(0:1, ncell(r), replace=TRUE)
    

    Aggregate

    a <- aggregate(r, 4, fun=function(x,...) 100 * mean(x))   
    # or 
    a <- 100 * aggregate(r, 4, mean)
    

    Consider NA values

    r[sample(ncell(r), 0.9 * ncell(r))] <- NA
    
    # Make a function and use it    
    percentage <- function(x, ...) { x <- na.omit(x); 100 * mean(x) }
    a <- aggregate(r, 4, fun=percentage)
    
    # or do
    a <- 100 * aggregate(r, 4, fun=mean, na.rm=TRUE)