7

I have a couple of RStudio projects that I've set up to automate tasks like grading multiple choice tests. The functions necessary to do the tasks are just saved in a text file, and to make sure they're available to me or other users I've been using an .Rprofile file that just runs something like source("MyFunctions.R") on startup. If an .Rprofile file is in the base directory of an RStudio project, it's automatically run when opening the project

However, I've run into occasional errors where functions provided by the base R packages aren't loaded before the script is sourced, functions like read.csv or installed.packages, e.g.:

Error in eval(expr, envir, enclos) : 
  could not find function "installed.packages"

Is there some way to wait for the default packages to load before source() is run, rather than adding explicit library() calls for all the default packages that fail to load?

Marius
  • 58,213
  • 16
  • 107
  • 105

2 Answers2

7

This, from ?Startup seems pretty definitive:

Note that when the site and user profile files are sourced only the 'base' package is loaded, so objects in other packages need to be referred to by e.g. 'utils::dump.frames' or after explicitly loading the package concerned.

Based on that explicit recommendation, using library() to load the necessary packages looks like your best bet.

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • Thanks, it looks I should rethink using `.Rprofile` for these kind of things. I'd been treating it as a quick and convenient way to automatically load functions and run scripts, and it doesn't seem like it really works like that. – Marius Nov 28 '12 at 00:46
  • If you haven't seen it yet, you might be interested in this SO [r]-tag classic: http://stackoverflow.com/questions/1189759/expert-r-users-whats-in-your-rprofile – Josh O'Brien Nov 28 '12 at 00:55
2

Having been pointed towards the ?Startup documentation by Josh's answer, it looks like adding a .First.sys() call at the top of .Rprofile may be an option, as that seems to be the function that handles loading of all the default packages. It is normally run after .Rprofile, which would explain the errors I was getting.

Marius
  • 58,213
  • 16
  • 107
  • 105