How to load packages automatically when opening a project in RStudio

In general there's nothing different to default package loading in RStudio than in R (How to load packages in R automatically?). Upon startup R checks for an .Rprofile file in either your local, or fail, that, home or install directory (on Mac/Linux: ./.Rprofile or else ~/.Rprofile) and executes it, and hence any options(defaultPackages...)) or other package-load-related commands it contains.

The only small difference is that RStudio "helpfully" changes your default path before startup see "RStudio: Working with Projects", so you might load a different or missing .Rprofile or the wrong .Rprofile, depending on whether you've opened an RStudio Project or just plain files, and what your RStudio default working directory is set to. It's not always clear what directory you're in, so sometimes this causes real grief.

I tend to use RStudio without defining my code as an RStudio Project, simply because it's heavy-handed and creates more files and directories without adding anything (to my use case, anyway). So the solution I found to maintaining .Rprofile and making sure the right one gets loaded is a trusty old Unix link from the project directory to my ~

ln -s ~/.Rprofile ./.Rprofile

(If you're on Windows it's more painful.)

You don't need to have one global .Rprofile, you could keep task-specific ones for different types of projects, or trees, or (say) a .Rprofile.nlp, .Rprofile.financial, .Rprofile.bio and so on. As well as options(default.packages, you can gather all your thematically-related settings: scipen, width, data.table/dplyr-specific options, searchpath...

Power tips:

  • obviously keep backups or SCM of your valuable .Rprofile(s)). Definitely make sure git is tracking it, so don't put it in .gitignore
  • if you have multiple .Rprofiles, put a cat("Loading .Rprofile.foo") line in each one so you can see from console that the right .Rprofile.xyz got loaded
  • after every project, revise, trim, tweak your .Rprofile; add new use case stuff, comment out irrelevant stuff, commit the changes to git

I presume you want to say that you have to reload all of the packages that were loaded in the workspace previously. That's not an error, that's by design.

If you want to load some packages at startup in a project, you can do so by creating a file called .Rprofile in the project directory, and specify whatever code you want RStudio to run when loading the project.

For example:

cat("Welcome to this project.\n")
require(ggplot2)
require(zoo)

would print a welcome message in the console, and load ggplot2 and zoo every time you open the project.

See also http://www.rstudio.com/ide/docs/using/projects

Tags:

R

Rstudio