Search code examples
rbashrscript

Load R packages only once when executing R scripts via bash


I have an R file example.r which basically looks like this:

#!/usr/bin/env Rscript
# do something ...
library(somelibrary)
# do something with somelibrary functions

And a bash script which needs to call Rscript example.r <PARAMETER> multiple times with different input parameters during one execution. My question is whether there is way to load the package somelibrary only once. Right now the package is loaded every time I call the script, which causes some overhead.


Solution

  • If you are launching a script like this:

    #!/usr/bin/env Rscript
    # do something ...
    library(somelibrary)
    # do something with somelibrary functions
    

    then each instance of it is a new process, a new fresh R process, and so any additional packages have to be attached using library. The overhead is unavoidable unless you want to run R as a service.