为 R 中的叠加层分配值?

Assign values to overlay in R?

我的问题是在为叠加层赋值时。

  library(raster)
  beginCluster(10)
  r <- raster(ncol=10, nrow=10)
  r1 <- init(r, fun=runif)
  r2 <- init(r, fun=runif)
  s=stack(r1,r2,r2,r1,r2,r1)
  wi=c(3,5,7)


  fun1 = function(x) {overlay(x, fun=function(x) movingFun(x, fun=mean, n=3))}
  vm = clusterR(s, fun1, progress = "text")

没问题!

但是当我将 n 分配给 wi 时它不起作用

 for(i in 1:3) {
   fun1 = function(x) {overlay(x, fun=function(x) movingFun(x, fun=mean, n=wi[i]))}
   vm = clusterR(s, fun1, progress = "text")
 }

我遇到了这个错误

cannot use this formula, probably because it is not vectorized"

函数内的所有内容都必须传递给它 - 由于集群的运行方式,它不会从您的环境中获取任何内容。

所以将 wii 传递给您的函数:

fun2 = function(x, wi, i) {
    overlay(x, 
     fun=function(x) movingFun(x, fun=mean, n=wi[i]))}

并在对 clusterR 的调用中将它们列为参数:

for(i in 1:3){
 vm = clusterR(s, fun2, list(wi, i), progress = "text")
}