将部分结果保存在R中的foreach循环中

时间:2018-10-02 15:47:32

标签: r foreach assign cat doparallel

我想知道已经完成了多少个循环并保存每个完成的循环的结果,但是assign和cat函数无法正常工作。

library(doParallel)
library(foreach)
library(Matrix)

rm(list=ls())


cl=makeCluster(2)
registerDoParallel(cl)

  sink("report.txt")
result=foreach (n=1:10,.packages="Matrix" )%dopar%{
  variable <-sparseMatrix(dims = c(100,150), i={1}, j={1},x=0)


  cat(sprintf("tastk %d is complete \n",n),append=TRUE)
  assign(paste("variable",n,sep=""),variable)
  return(variable)

} 

sink()

1 个答案:

答案 0 :(得分:0)

这在我的Linux计算机上可以很好地工作:

library(doParallel)
library(foreach)
library(Matrix)

rm(list=ls())


cl=makeCluster(2, outfile = "report.txt")
registerDoParallel(cl)

result=foreach (n=1:10,.packages="Matrix" )%dopar%{

  variable <-sparseMatrix(dims = c(100,150), i={1}, j={1},x=0)      

  cat(sprintf("task %d is complete \n",n))
  assign(paste("variable",n,sep=""),variable)
  return(variable)

} 

stopCluster(cl)