# Example: Accessing environment variable named API_KEY
api_key <- Sys.getenv("API_KEY")
api_key[1] ""
Setting up and using environment variables in R is useful for handling configuration details and/or suppressing private information.
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.
Environment variables can be set in R by using Sys.setenv().
Sys.setenv(API_KEY = "your_api_key").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.
Avoid using spaces around the = sign.
# Example .Renviron file
API_KEY=your_api_key.Renviron from R using browseURL() or usethis packageThe .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()dotenv for managing environment variables?