在foreach()中运行system()

时间:2018-04-02 15:47:46

标签: r foreach parallel-processing system

我在Windows 7上运行R版本3.4.1。

我需要使用存储在工作目录中的N = 500个引导数据文件来运行某个程序。可执行文件将为N次运行中的每次运行生成3个以上的数据文件,所有这些文件都存储在一个工作目录中。我想使用并行计算来提高此过程的速度。

循环需要一个起始文件(' starter'),它在循环的每次迭代时都会被修改。这是一个非常重要的部分,我无法真正做到这一点。此外,在每次迭代时,都会删除任何预先存在的数据文件,然后使用system()调用可执行文件。可执行文件生成三个名为Report,CompReport和covar的数据文件。

在正常循环中,过程如下所示:

starter_strt <- SS_readstarter(file="starter.ss") # read starter file
    for(iboot in 1:N){
     starter$datfile <- paste("BootData", iboot, ".ss", sep="")

     #code to replace the starter file with the new one
     SS_writestarter(starter, overwrite=TRUE)

     #any old files are removed
     file.remove("Report.sso", paste("Report_",iboot,".sso",sep=""))
     file.remove("CompReport.sso", paste("CompReport_",iboot,".sso",sep=""))
     file.remove("covar.sso", paste("covar_",iboot,".sso",sep=""))

     #then the program is called
      system("ss3")
     #the files produced get pushed to the working directory
     file.copy("Report.sso",paste("Report_",iboot,".sso",sep=""))
     file.copy("CompReport.sso",paste("CompReport_",iboot,".sso",sep=""))
     file.copy("covar.sso",paste("covar_",iboot,".sso",sep=""))
    }

上述过程需要5天才能完成,因此我一直在探索并行化的选项。到目前为止,我所使用的工作并不起作用,因此我们对任何帮助或建议表示赞赏。这就是我的想法。使用foreach循环并确保我没有读取和覆盖起始文件。这就是我所拥有的:

# read starter file

starter_strt <- SS_readstarter(file="starter.ss") # read starter file
iter <- 2 #just for an example here even though I said N=500 above
cores <-  parallel::detectCores()-1
cl <- makeCluster(cores)
registerDoParallel(cl)
clusterCall(cl, function(x) .libPaths(x), .libPaths())   

foreach(iboot=1:iter, .packages='r4ss', .export="starter_strt", system          ("ss3")) %dopar% {

  #code to create the starter file so I don't overwrite it 
  datfile<- data.frame(rep(paste("BootData",iboot,".ss",sep=""),2))
  colnames(datfile) <- "datfile"
  starter_list <- cbind(starter_strt, datfile)

  # replace starter file with modified version
  SS_writestarter(starter_list, overwrite=TRUE)

  #delete files as above
  #run program
   system("ss3")
 #the files produced get pushed to the working directory
 file.copy("Report.sso",paste("Report_",iboot,".sso",sep=""))
 file.copy("CompReport.sso",paste("CompReport_",iboot,".sso",sep=""))
 file.copy("covar.sso",paste("covar_",iboot,".sso",sep=""))

}

程序运行一次,但后来我收到警告(见下文)并且目录中缺少预期的文件。

Warning message:
In e$fun(obj, substitute(ex), parent.frame(), e$data) :
  already exporting variable(s): starter_strt

我在这一点上很难过。我看到了这个例子Running multiple R scripts using the system() command,其中在parLapply函数中调用了系统命令。也许这就是我需要的?非常感谢帮助和/或建议。

0 个答案:

没有答案