2016-10-30 28 views
0

我想知道是否可以并行写入pdf文件。我有很多功能,每个功能都写了很多数字。这是按顺序完成的,需要相当长的时间。R,并行写入pdf

举个简单的例子:

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

我试图使其平行这样的:

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) 

即使功能并行执行,我得到一个空的PDF文件。

感谢您的任何建议。

回答

0

如提到here,您不能并行绘制到同一个设备。

但是,就并行处理而言,下面的代码会影响工作。但同样,由于上述原因,输出不是你想要的。

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

感谢您的回复,但我也同时实现的代码,所以我没有看到用parLapply重写它的原因。并感谢您的链接。看起来像是真的不可能 –