简体   繁体   中英

save partial results in foreach loop in R

I want to know how many loops have been done and save the results of each finished loop, but assign and cat function are not working.

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()

This works perfectly fine on my Linux computer:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM