[GIS] How to aggregate a raster in R using a quantile function

rraster

I'm trying to create a new, smaller NDVI raster with the upper quantile of raster values for the new aggregated cells.

library(raster)
rast <- raster("ndvi.tif")

Now I'd like to create the new raster downsampled by a factor of 10, using a quantile function for the top 25% of the data:

rast2 <- aggregate(x = rast, fact = 10, 
    fun = function(i) quantile(i, probs = 0.75, na.rm = T))

This always gives an error:

Error in FUN(newX[, i], ...) : unused argument (na.rm = TRUE)
Called from: FUN(newX[, i], ...)

If I use mean or max it works just fine, only quantile gives an error. I've also tried defining a custom function but with the same result.

Best Answer

aggregate is passing an na.rm function to your fun function:

rast2 <- aggregate(x = rast, fact = 10, 
    fun = function(i) quantile(i, probs = 0.75, na.rm = T))

But fun is only function(i) so it fails. You can fix this either by:

   fun = function(i,...) quantile(i, probs=0.75, na.rm=T))

to ignore any na.rm values, or possibly:

   fun = function(i, na.rm) quantile(i, probs=0.75, na.rm=na.rm))

which will pass through any na.rm value passed to aggregate.

This is documented in the help for raster::aggregate:

  The function ‘fun’ should take multiple numbers, and return a
     single number. For example ‘mean’, ‘modal’, ‘min’ or ‘max’.  It
     should also accept a ‘na.rm’ argument (or ignore it as one of the
     'dots' arguments).
Related Question