Problem: You’re using an API and you need to provide your key or token to authenticate yourself. You don’t want to do this interactively and repeatedly. You don’t want to store the key in your scripts or push it to GitHub by mistake.

Solution: Store it as an environment variable and retrieve it with Sys.getenv() in an R script or an RMarkdown document.

Motivating example: I use this method to interact with GitHub via the github R package, a wrapper around the Github v3 API.

Source: The httr package has a vignette, Best practices for writing an API package, that advocates this approach (but lacks this excruciating detail).

How to do it:

FAQ: Why define this environment variable via .Renviron instead of in .bash_profile or .bashrc?

Because there are many combinations of OS and ways of running R where the .Renviron approach “just works” and the bash stuff does not. When R is a child process of, say, Emacs or RStudio, you can’t always count on environment variables being passed to R. Put them in an R-specific start-up file and save yourself some grief.