r - Evaluating text within a raster calc function -


i evaluate text argument in raster calculate function use parallel processing in r raster package map function.

the code below works fine (but not desirable):

library(raster) library(snow) library(doparallel)  # using rasterstack input r <- raster(ncols=36, nrows=18) r[] <- 1:ncell(r) s <- stack(r, r*2, sqrt(r))  # create raster calculation function f1<-function(x) calc(x, fun=function(x){ rast<-(x[1]/x[2])*x[3];return(rast) })  # map using parallel processing capabilities (via clusterr in raster package) begincluster() pred <- clusterr(s, fun=f1, filename=paste("test.tif",sep=""),format="gtiff",progress="text",overwrite=t) endcluster() 

i prefer above raster calculation function line of text can evaluated in raster function itself, this:

#create equivalent string argument str<-"rast<-(x[1]/x[2])*x[3];return(rast)"  #evaluate in raster calculation function using eval , parse commands f1<-function(x) calc(x, fun=function(x){ eval(parse(text=str)) })  #map using parallel processing capabilities (via clusterr in raster package) begincluster() upper_pred <- clusterr(s, fun=f1, filename =paste("test.tif",sep=""),format="gtiff",progress="text",overwrite=t) endcluster() 

unfortunately, method falls on in clusterr function.

what need in order second method work? seems eval command not recognized in raster calculation. have many string arguments structured , evaluate each 1 without having manually copy/paste console.

thanks help!

i suspect it's because function refers str defined in global environment of main r process not exported cluster. 1 option might neater anyway produce function str:

f1 <- eval(parse(text = paste0("function(x) calc(x, fun = function(x){", str, "})"))) 

you have function this:

make_f1 <- function(str) {   eval(parse(text = paste0("function(x) calc(x, fun = function(x){", str, "})"))) } f1 <- make_f1(str) 

it's worth noting particular example simplified to:

str<-"x[1]/x[2])*x[3]" 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -