在栅格计算函数中评估文本

3

我希望能够在一个栅格计算函数中评估文本参数,然后使用R栅格包中的并行处理来映射该函数。

下面的代码可以正常工作(但不理想):

library(raster)
library(snow)
library(doParallel)

# using a RasterStack as input
r <- raster(ncols=36, nrows=18)
r[] <- 1:ncell(r)
s <- stack(r, r*2, sqrt(r))

# create the raster calculation function
f1<-function(x) calc(x, fun=function(x){
rast<-(x[1]/x[2])*x[3];return(rast)
})

# Map it using parallel processing capabilities (via clusterR in the raster package)
beginCluster()
pred <- clusterR(s, fun=f1, filename=paste("test.tif",sep=""),format="GTiff",progress="text",overwrite=T)
endCluster()

我希望上述栅格计算函数可以作为文本行在栅格函数中进行评估,类似于这样的形式:
#Create the equivalent string argument
str<-"rast<-(x[1]/x[2])*x[3];return(rast)"

#Evaluate it in the raster calculation function using eval and parse commands
f1<-function(x) calc(x, fun=function(x){
eval(parse(text=str))
})

#Map it using parallel processing capabilities (via clusterR in the raster package)
beginCluster()
upper_pred <- clusterR(s, fun=f1, filename =paste("test.tif",sep=""),format="GTiff",progress="text",overwrite=T)
endCluster()

不幸的是,这种方法在ClusterR函数中会失败。

为了使第二种方法起作用,我需要做些什么?似乎raster计算中没有识别eval命令。我有很多像这样结构化的字符串参数,并希望评估每个参数,而无需手动复制/粘贴到控制台中。

感谢您的帮助!

1个回答

0
我怀疑这是因为该函数引用了str,而str在您的主R进程的全局环境中定义,但未导出到集群。一个更好的选择是从str生成一个函数,这样可能更整洁:
f1 <- eval(parse(text = paste0("function(x) calc(x, fun = function(x){", str, "})")))

你甚至可以有一个函数来完成这个操作:
make_f1 <- function(str) {
  eval(parse(text = paste0("function(x) calc(x, fun = function(x){", str, "})")))
}
f1 <- make_f1(str)

值得注意的是,你的特定示例可以简化为:
str<-"x[1]/x[2])*x[3]"

非常感谢你,尼克!你的代码解决了问题,我同意它更加简洁。 - Mat W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接