Environment Variables in R Programming Language

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in R.

# To set a key/value pair, use Sys.setenv(). To get a
# value for a key, use Sys.getenv(). This will return
# an empty string if the key isn't present in the
# environment.

Sys.setenv(FOO = "1")
cat("FOO:", Sys.getenv("FOO"), "\n")
cat("BAR:", Sys.getenv("BAR"), "\n")

# Use Sys.getenv() without arguments to list all key/value pairs in the
# environment. This returns a named character vector.
# Here we print all the keys.

cat("\n")
env_vars <- Sys.getenv()
for (key in names(env_vars)) {
  cat(key, "\n")
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ Sys.setenv(BAR="2")
$ Rscript environment-variables.R
FOO: 1
BAR: 2
...

In R, environment variables are managed using the Sys.setenv() and Sys.getenv() functions. The Sys.getenv() function without arguments returns all environment variables as a named character vector, which we can iterate over to get all keys.