Load Packages Automatically in RStudio

I recently finished a long stretch of work on a particular project that required me to draw upon four R packages.  Each time I got back to my work on the project, I’d have to load the packages manually, as needed.  It got really annoying and constantly made me wonder whether there was some way that I could just get these packages loaded automatically every time I switched to that project in R Studio so that I didn’t have to waste my time.

I finally got around to looking for an answer, and found it on an R Studio suggestions forum.  You create a .Rprofile file in your project directory within R Studio (see example below) or from a text editor, and then just type the library commands that call the R packages that you want.  Save it, and now every time you switch to your project in R Studio, the packages most relevant to your project will be loaded automatically!  See an example below of making the file from within R Studio:

> file.edit("~/Desktop/foo/.Rprofile")
# This opens up a script window, within which you can enter in your library commands



4 thoughts on “Load Packages Automatically in RStudio

  1. Had a similar problem. Just put all packages to be loaded in a single line and seperate them with semicolons to execute multiple commands per line

    • I’ve also made this function which seems to work (though there are surely beautifuller ways to do it.)

      libraries <- function(x) lapply(x, require, character.only=T)

      libraries(c("ggplot2", "scales", "plyr", "reshape"))

  2. By default the contents of the variable ‘defaultPackages’ packages are loaded so I choose to extend that vector in my .Rprofile as follows:

    r <- getOption("defaultPackages")
    r <- c(r, "knitr")
    options("defaultPackages" = r)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s