I am encountering difficulties saving data related to "abc" into a file named "myResults.rds". My code is complex and involves multiple operations within a foreach loop. I wish to exclusively save a particular outcome that I have stored in a list named "abc". Here is an illustration of the code:
library(foreach)
library(doParallel)
# create a cluster with 6 workers
cl <- makeCluster(6)
registerDoParallel(cl)
# define a local function
generate<-function(p){
MIN <- (1-p)*100
MAX <- (1+p)*100
print(paste(MIN,MAX))
mat <- matrix(nrow=1,ncol=4)
for (i in seq(1,11,1)){
a <- round(runif(1,MIN,MAX),2)
b <- round(runif(1,MIN,MAX),2)
c <- round(runif(1,MIN,MAX),2)
d <- round(runif(1,MIN,MAX),2)
mat <- rbind(mat,c(a,b,c,d))
}
return(mat[2:length(mat[,1]), ])
}
# run the loop with foreach and call the local function in parallel
abc<-list()
results <- foreach(i = 1:3) %dopar% {
lstData=generate(0.05)
abc[[i]]=lstData
# main code goes here for analysis ......
# Just added two simple operations for cheeking
addNum <- 1+2+3
subNum <- 1-2-3
}
saveRDS(abc, file = "myResults.rds")
stopCluster(cl)
Here is another approach that can be considered :