R Script and Library preloading?

2019-07-20 04:32发布

问题:

I have created an R script that it needs to load some libraries first.

The problem is that the script needs 1.6 seconds to finish its calculations (measured it many times with Linux command "time") and 0.7 seconds only takes to load the libraries!

The script runs quite often, so the delay for library loading accounts to almost 80% of the real workload!

Is there any way to have the libraries preloaded so that they won't be loaded each time the script runs?

Any other suggestion to bypass this slowness?

#!/usr/bin/Rscript

library(methods, quietly=TRUE, warn.conflicts = FALSE)
library(MASS, quietly=TRUE, warn.conflicts = FALSE)
library(RBGL, quietly=TRUE, warn.conflicts = FALSE)
library(igraph, quietly=TRUE, warn.conflicts = FALSE)
library(bnlearn, quietly=TRUE, warn.conflicts = FALSE)
library(gRbase, quietly=TRUE, warn.conflicts = FALSE)
library(gRain, quietly=TRUE, warn.conflicts = FALSE)
..
..

回答1:

If you turn your script into a package (which you should anyway, in the longer run ...) then you can use Imports of just the symbols you need from the packages you use -- which is typically a tad faster than a full load as done by Depends.

So the key is to

  1. use a package
  2. learn about NAMESPACE
  3. import just the symbols you need.

An orthogonal approach would be not to restart and to save that time --- you could use Rserve as a resident R instance and just connect to it with an R client. Probably more work though...