Error using calc() function: cannot use this function

坚强是说给别人听的谎言 提交于 2021-01-28 09:08:09

问题


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

回答1:


From calc help:

For large objects calc will compute values chunk by chunk. This means that for the result of fun to be correct it should not depend on having access to all values at once. For example, to scale the values of a Raster* object by subtracting its mean value (for each layer), you would not do, for Raster object x:

calc(x, function(x)scale(x, scale=FALSE))

Because the mean value of each chunk will likely be different. Rather do something like

m <- cellStats(x, 'mean')

x - m

therefore, your function, even if it worked, would probably give you incorrect results. I'm not entirely sure why the function doesn't work, however: maybe there ìs an internal check in calc to avoid the use of cellStats.

To do "your" computation, however, you could use simply:

out = s
for (i in 1:nlayers(s)) {

  out [[i]] = (s [[i]] - cellStats(s[[i]], 'min', na.rm = T))*5

}


来源:https://stackoverflow.com/questions/42327823/error-using-calc-function-cannot-use-this-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!