[GIS] R – aggregate with additional argument

aggregationfunctionr

I would like to use the function aggregate (R raster package) to assign to a grid point of the new raster the number of grid points of the old raster that have a certain value

for(val in 1:10)
{
    new.raster <- aggregate(old.raster, 10, fun = function(x) length(x[x == val], na.rm=TRUE))

    #...some computation involving new.raster...
}

I've moved "na.rm = TRUE" around in every way imaginable, but R keeps complaining about an "Error in FUN(newX[, i], …) : unused argument (na.rm = TRUE)". Any ideas?

If it's possible to write this piece of code in a more efficient manner (having the function fun outside the aggregate function, or the like), I'd be happy if you could let me know as well, as I'm running the code for a very large number of rasters.

Best Answer

From the documentation:

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

You've just got function(x), which has neither an na.rm or dots in it.

Try:

new.raster <- aggregate(old.raster, 10, fun = function(x,...) length(x[x == val]))

to ignore whatever na.rm is passed through to it, or:

new.raster <- aggregate(old.raster, 10, fun = function(x, na.rm) length(x[x == val]))

to (maybe) pass through any na.rm in the aggregate call.

Note untested, because no reproducible example.. But it looks right.

Also, instead of length(x[x==val]) you might be better with sum(x==val, na.rm=na.rm) and then you can pass the na.rm through to handle possible NA in your data.