I need to run calculations on large multi-band rasters and export a RasterBrick, and am trying to do so using the calc() function in the raster package, for the purpose of memory efficiency. The function runs fine on its own, but when I try to include it in calc(), I keep getting this error:

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : cannot use this function

How can I make this work?

Simplified code:

fn = system.file("external/test.grd", package="raster")
s = stack(fn, fn, fn, fn)

out = calc(s, fun = function(x){
  for (i in 1:nlayers(x)){
    x[[i]] = x[[i]] - cellStats(x[[i]], "min")
    x[[i]] = x[[i]]* 5
  list = unstack(x)
  out = brick(list)

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : 
  cannot use this function
  • 3
    Get rid of your for loop, unstack and brick calls. Take a look at the help for calc and overlay. The function expects a vectorized function and not one that attempts to manipulate the raster or stack explicitly. Looping through layers in a stack is performed within calc or overlay. – Jeffrey Evans Feb 19 '17 at 16:18
  • @JeffreyEvans Looks like your comment could become an answer with no or little expansion. – PolyGeo Feb 21 '17 at 22:52

calc iterates through layers of a Raster Stack on its own, so a for loop and indexing is not necessary here. Removing them, as well as the unstack and brick fixes the problem.

| improve this answer | |

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.