使用 calc() 函数时出错:无法使用此函数 [英] Error using calc() function: cannot use this function
问题描述
我需要在大型多波段栅格上运行计算并导出 RasterBrick,并且我正在尝试使用栅格包中的 calc()
函数来执行此操作,以提高内存效率.该函数本身运行良好,但是当我尝试将它包含在 calc()
中时,我不断收到此错误:
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:
.calcTest(x[1:5], fun, na.rm, forcefun, forceapply) 中的错误:无法使用此功能
我怎样才能做到这一点?
How can I make this work?
简化代码:
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
推荐答案
来自 calc
帮助:
对于大对象,calc 将逐块计算值.这意味着对于乐趣的结果是正确的,它不应该依赖于一次访问所有值.例如,要缩放Raster* 对象的值减去其平均值(对于每个层),对于 Raster 对象 x,您不会这样做:
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))
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')
m <- cellStats(x, 'mean')
x - 米
因此,即使您的函数有效,也可能会给您错误的结果.我不完全确定为什么该函数不起作用,但是:也许 calc
中有一个内部检查来避免使用 cellStats
.
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
}
这篇关于使用 calc() 函数时出错:无法使用此函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!