Search code examples
rforeachparallel-processingdoparallelopenxlsx

How to insert a plot over foreach() loop?


Is is possible to add plot inside a foreach()% dopar{} loop?

I'm using the below code, but it does not insert the image using foreach. It works perfectly with the for-loop though.

How it works over a foreach loop?

{rm(list = ls())
  library(dplyr)
  library(imager)
  library(openxlsx)
  }

library(foreach)
library(doParallel)
cl <- makeCluster(4)
registerDoParallel(cl)

#for(i in 1:3){ 
foreach(i = 1:3, .combine = cbind, .packages = c("dplyr","imager","openxlsx"))%dopar% {
     file<-paste0(i,".xlsx")
     wb<-createWorkbook(file)
     addWorksheet(wb, "test", gridLines = T)
     Logo<- imager::load.image("~/YY.PNG")
     print(Logo)
     insertPlot(wb, sheet = "test", width = 2, height =1, fileType = "png", units = "in")
     saveWorkbook(wb, file, overwrite = TRUE)
  }
stopCluster(cl)

Solution

  • Thanks to @MrFlick, the answer is as below:

    library(foreach)
    library(doParallel)
    cl <- makeCluster(4)
    registerDoParallel(cl)
    
    foreach(i = 1:3, .combine = cbind, .packages = c("dplyr","imager","openxlsx"))%dopar% {
      file<-paste0(i,".xlsx")
      wb<-createWorkbook(file)
      addWorksheet(wb, "test", gridLines = T)
      img <- "~/YY.png"
      insertImage(wb, sheet = "test", img, width = 2, height =1, units = "in",startRow = 1, startCol = 1)
      saveWorkbook(wb, file, overwrite = TRUE)
    }
    stopCluster(cl)