简体   繁体   English

R,并行写入pdf

[英]R, write into pdf in parallel

I am wondering about possibility to write into pdf file in parallel. 我想知道是否可以并行写入pdf文件。 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. 即使功能是并行实现的,我也会得到一个空的PDF文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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