Bug: ggsave() does not work when called in mclapply() in RStudio IDE (same code works perfect at CLI)

ggplot2
rstudio
parallel

#1

I have a need to plot and save graphs from ggplot() to a file inside of the parallel version of lapply(), mclapply(). The following code snippet reproduces the problem. When run inside RStudio, no files are generated, no errors/warnings occur, 50% of the time mclapply() does not return, and the other 50% of the time it returns 5 NULL values. When run from the command line (Linux or macOS), it works 100% of the time, generates all the PNG files, and returns the values 0 through 4:

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

RStudio version is 1.1.419.

> R.version
               _
platform       x86_64-apple-darwin15.6.0
arch           x86_64
os             darwin15.6.0
system         x86_64, darwin15.6.0
status
major          3
minor          4.4
year           2018
month          03
day            15
svn rev        74408
language       R
version.string R version 3.4.4 (2018-03-15)
nickname       Someone to Lean On
> Sys.info()
                                                                                          sysname
                                                                                         "Darwin"
                                                                                          release
                                                                                         "17.5.0"
                                                                                          version
"Darwin Kernel Version 17.5.0: Mon Mar  5 22:24:32 PST 2018; root:xnu-4570.51.1~1/RELEASE_X86_64"
                                                                                         nodename
                                                                                   "farmac.local"
                                                                                          machine
                                                                                         "x86_64"
                                                                                            login

NOTE: the code works fine in RStudio if you change parallel::mclapply() to base::lapply() (it's just not parallelized), and I've also tried using png()/dev.off() in place of ggsave() and experience the same phenomenon.