I would like to use the R 'parallel' library to parallelize generating some plots using the 'ggplot2' library and have run into a snag when attempting to do this within RStudio. Within the IDE, mclapply alternately freezes the session, or fails to run ggsave() to write a plot to disk (no errors or warnings are given). It works perfectly 100% of the time when run outside of RStudio. I'm guessing that RStudio is doing something nasty with graphics devices, but I can't figure out what or a work around (I've tried png()/dev.off() too, same problem). Here's code that reproduces the problem:
library(ggplot2)
library(parallel)
mclapply(
0:4,
function(n) {
df <- data.frame(x = runif(10), y = runif(10))
p <- ggplot(df, aes(x, y)) + geom_point()
ggsave(
paste0('mclapply-', n, '.png'),
plot = p,
device = 'png',
width = 4,
height = 4
)
return(n)
}
)
Any suggestions for a work-around?
EDIT: R 3.4.4 + RStudio 1.1.419 + ggplot2 2.2.1 on macOS 10.13.4; mclapply() reverts lapply() on Windows (where it's not supported).