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.


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.


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.

  • Both suggestions result in "Error in length([...]) : 2 arguments passed to 'length' which requires 1" – user90855 Feb 2 '17 at 18:53
  • Ah yes, get rid of the na.rm in your call to length because it doesn't take that parameter - see edit. – Spacedman Feb 2 '17 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.