What is the best way to set environment variables on a Mac for use within an RStudio session.

Overview

Generally, you can set environment variables by:

export YOUR_VAR=abc123

within a terminal. In a new session,

echo $YOUR_VAR

should yield what you need.

Within Python, you can get at it by:

import os
os.getenv("YOUR_VAR")

But if you are using R and RStudio, Sys.getenv("YOUR_VAR") returns"".

No bueno.

A solution

Navigate to ~, and create the .Renviron file if it doesn’t already exist

cd ~
touch .Renviron
open .Renviron

And in the file, type

YOUR_VAR="abc123"

Save the file and restart/reopen RStudio.

From there, Sys.getenv("YOUR_VAR") should be good to go.

Deeper Dive

For a more granular look at this functionality, feel free to reference the links below: