2  R Environment Variables

Setting up and using environment variables in R is useful for handling configuration details and/or suppressing private information.

2.1 Retrieve/access environment variables:

Values stored in the system environment can be retrieved using Sys.getenv("VAR_NAME").

# Example: Accessing environment variable named API_KEY
api_key <- Sys.getenv("API_KEY")
api_key
[1] ""

In the case where the value might not be found, make sure to specify an unset value that acts as a default.

# Example: Accessing environment variable named API_KEY
api_key <- Sys.getenv("API_KEY", unset = NA)
api_key
[1] NA

Note, the Sys.getenv() function only returns a character value.

2.2 Set environment variables in your R environment

Environment variables can be set in R by using Sys.setenv().

Sys.setenv(API_KEY = "your_api_key")

2.3 Use an .Renviron file for configuration:

Frequently using environment variables? Instead of defining them for each script, aim to store environment variables in a .Renviron file in the project directory.

Variables are specified in the .Renviron file with the format VAR_NAME=value.

Note

Avoid using spaces around the = sign.

# Example .Renviron file
API_KEY=your_api_key

2.4 Access .Renviron from R using browseURL() or usethis package

The .Renviron file may be accessed using either browseURL("~/.Renviron") or with usethis::edit_r_environ() for editing.

# Example: Load .Renviron file with browseURL()
utils::browseURL("~/.Renviron")
# Example: Load .Renviron file with the usethis package
usethis::edit_r_environ()

2.4.1 TODO: mention dotenv for managing environment variables?