Customizing your .rprofile

September 29, 2011

I searched around to see if there was a blog post somewhere describing how to customize one’s .rprofile but was surprised to find just one outdated post. So here is quick intro on the topic. If you are a power R user, you already know about what it does. For those of you that don’t, it is just a text file called .rprofile that sits in your R home directory (not sure where it is? Instructions to find it on a pc or a mac) and all of the commands in there are executed at startup.

  1. Load frequently used packages
    These days I never run R without having to use ggplot2 or plyr so I just include that here (although I hope that someday both packages will become absorbed into the R core).

  2. Create aliases for frequently used functions
    # Shorten S3 methods so s(obj) instead of summary(obj)
    s <- base::summary;
    h <- utils::head;
    n <- base::names;
  3. Set your preferred repository

    Hate the menu that asks you to choose a repository when installing a package? Just hardcode it.

    # Get your current repo name
    current_repo <- getOption("repos") 
    # change this to your closest one
    current_repo["CRAN"] <- ""
    options(repos = current_repo)
  4. Create a new environment so you don’t lose your custom startup functions

    I always start a new script with rm(list=ls()) to clear out everything. The unfortunate consequence of this is that it also takes out all the cool new functions from your .rprofile. Get around that by creating a new environment and putting your functions there.

    custom_env <- new.env()
    # If you don't want to clutter this file, leave functions elsewhere.
    sys.source(".my_custom_functions.r", envir = custom_env)

You can also set a range of other options but these are a good start.

Update: As Jason Priem astutely points out, these tricks can impede reproducibility of your work (especially if you fail to load the appropriate libraries & functions in your final script). While these are valuable time savers during the development phase, you certainly want to be more thorough before sharing your code.

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.