2015-07-11 49 views
2

我会在光栅计算函数中计算文本参数,然后在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函数中。

为了让第二种方法起作用,我需要做些什么?看来eval命令在光栅计算中不被识别。我有很多像这样构造的字符串参数,并且想要评估每个字符串参数而不必手动复制/粘贴到控制台。

感谢您的帮助!

回答

0

我怀疑这是因为该函数引用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]" 
+0

非常感谢,尼克!你的代码完成了这个诀窍,我同意它很简单。 –