我需要在大型多波段栅格上运行计算并导出RasterBrick,并尝试使用栅格包中的calc()
函数来实现内存效率。该函数可以自行运行,但是当我尝试将其包含在calc()
中时,我不断收到此错误:
Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
cannot use this function
我该如何做到这一点?
简化代码:
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
答案 0 :(得分:1)
来自calc
帮助:
对于大对象,calc将按块计算值块。 这意味着,为了使乐趣的结果是正确的,它不应该依赖 可以立即访问所有值。例如,要缩放 Raster *对象的值减去其平均值(对于每个值) 对于Raster对象x:
,你将不做calc(x,function(x)scale(x,scale = FALSE))
因为每个块的平均值可能会有所不同。宁 做点什么
m< - cellStats(x,'mean')
x - m
因此,您的功能即使有效,也可能会给您不正确的结果。我不完全确定为什么函数不起作用:可能会在calc
中进行内部检查以避免使用cellStats
。
要进行“你的”计算,你可以简单地使用:
out = s
for (i in 1:nlayers(s)) {
out [[i]] = (s [[i]] - cellStats(s[[i]], 'min', na.rm = T))*5
}