简体   繁体   中英

R, write into pdf in parallel

I am wondering about possibility to write into pdf file in parallel. I have quite a few functions and each of them is writing many figures. This is done sequentially and takes considerable amount of time.

As a simple example:

plot1 <- function() plot(c(1, 2, 3, 4, 5), type="o", col="blue")
plot2 <- function() plot(c(5, 4, 3, 2, 1), type="o", col="blue")

pdf("PDFname.pdf", width = 12, height = 10)
plot1()
plot2()
dev.off()

I was trying to make it parallel like this:

library (parallel)

plots <- list(
  plot1 <- function() plot(c(1, 2, 3, 4, 5), type="o", col="blue"),
  plot2 <- function() plot(c(5, 4, 3, 2, 1), type="o", col="blue")
)


cl <- makeCluster(2);

pdf("PDFname.pdf", width = 12, height = 10)
clusterApply(cl, plots, function(func) func())
dev.off()

stopCluster(cl)

Even though the functions are implemented in parallel, I get an empty PDF file.

Thanks for any suggestions.

As mentioned here , you cannot plot to the same device in parallel.

But as far as parallel processing concerns the following code does the job. But again, the output is not what you want because of the aforementioned reason.

library(parallel)

plots <- list(
  plot1 <- function() plot(c(1, 2, 3, 4, 5), type="o", col="blue"),
  plot2 <- function() plot(c(5, 4, 3, 2, 1), type="o", col="blue")
)

# getting the number of cores
no_cores <- detectCores() - 1

# Initiate the cluster
cl <- makeCluster(no_cores)

# make the function available
clusterExport(cl, "plots")

pdf("PDFname.pdf", width = 12, height = 10)

# parallel call
parLapply(cl, 1:length(plots),
          function(i) {
            plots[[i]]()})

stopCluster(cl)
dev.off()

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