3

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)
  return(out)
}
)

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : 
  cannot use this function
2
  • 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. Commented Feb 19, 2017 at 16:18
  • @JeffreyEvans Looks like your comment could become an answer with no or little expansion.
    – PolyGeo
    Commented Feb 21, 2017 at 22:52

1 Answer 1

0

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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