Setting R's default behaviour in .Rprofile and .Renviron. Understanding what to do where

1.1k Views Asked by At

I am trying to understand the use of the files .Renviron and .Rprofile. If I understand correctly, the .Rprofile is sort of a startup script, sourced as R code, that sets the options and environment variables that a user may want either all the time, or for a specific project. On the other hand .Renviron is loaded before .Rproject, and defines environment variables only.

By design I understand that R will load either the user or the project level .Renviron and .Rprofile files, but it won't load both user and project level files. Essentially, R will only load the project specific .Rprofile and .Renviron files, provided they are defined. That said, some libraries and functions would be prudent to put in the user level .Rprofile, as I need it pretty much all the time (e.g. I use dplyr syntax a lot), while at the same time I'd like to load project specific libraries and functions as well.

The purpose of the .Renviron file is more elusive to me. From what I understand, its purpose is to store environment variables, such as passwords, API keys, etc.. However, I can also set environment variables in .Rprofile using Sys.setenv(). For example, I have the environment variable set in a project's .Rprofile, to use parallelization with the package below:

Sys.setenv(OMP_NUM_THREADS=parallel::detectCores())
library(OpenMx)

Since the .Renviron doesn't use code, my assumption is I could've put this line in a .Renviron file with the following syntax:

OMP_NUM_THREADS=[number of cores]

However, I find little useful information on how to set environment variables in .Renviron, and what is advisable to put here.

My questions therefore are:

  1. How can I load both user and project level .Renviron and .Rproject files when working in a project?
  2. What environment variables would I typically put in .Renviron? (Any list or tutorials on how to set variables would be appreciated.)
  3. In which cases would it be recommended to add environment variables to .Renviron over using Sys.setenv() in .Rprofile, and vice versa?
1

There are 1 best solutions below

0
On

However, I can also set environment variables in .Rprofile using Sys.setenv().

"Yes but" these can under standard POSIX behaviour not alter the running process for which the variables have to be set before.

I just like you tried to get by for as long as I could with only ~/.Rprofile (or even just Rprofile.site for the whole machine) but eventually added things in .Renviron for

  • R_LIBS_USER to "" as I prefer not to have installations below ~
  • R_MAX_NUM_DLLS which has to be here
  • plus a few tokens for services
  • plus a reticulate option
  • plus a R CMD check option

so in some cases you do in fact have to use .Renviron (or Renvirob.site).