Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Renviron variables not found when Rscript run from powershell?

Tags:

r

renviron

I have an R script that runs perfectly when run from Rstudio. It uses an .Renviron file to provide environment variables which are visible in Sys.getenv() (so I know it works).

However, when I run the exact same script via powershell, the R script mysteriously doesn't find those environment variables (I confirmed this by print(Sys.getenv()) - the environment variables provided through .Renviron are nowhere to be seen.

Question

Why aren't the .Renviron variables being found when the R script is run from powershell (as opposed to when the script is run in RStudiom, where everything works)

What I've tried

The .Renviron file is currently saved in "C:/Users/Administrator/Documents/.Renviron"

Inspecting normalizePath(Sys.getenv('R_HOME')) returns "C:\\Program Files\\R\\R-3.6.0", so I also tried putting .Renviron there. No luck

Based on this I also tried Sys.getenv("C:/Users/Administrator/Documents/.Renviron"), but again no luck

like image 818
stevec Avatar asked Jul 10 '19 12:07

stevec


3 Answers

I had the same problem: .Renviron files were being completely ignored on Windows.
I thought that what finally worked was reinstalling R (I had R 3.6, installed R 4.0).

But it turns out I was wrong. The magic sauce is adding --cd-to-userdocs to the R.exe or Rscript.exe command. I couldn't find documentation for this option anywhere, and it doesn't show up in command line parameters help, but it works.

like image 100
Zbyl Avatar answered Nov 18 '22 16:11

Zbyl


This is what worked for me

path_to_Renviron_file <- "C:/Users/Administrator/Documents/.Renviron"
readRenviron(path_to_Renviron_file) 
like image 3
stevec Avatar answered Nov 18 '22 18:11

stevec


RScript performs the same initialisation as normal R, unless this is specifically disabled with command line options (--no-environ). The .Renviron and .Rprofile files are searched for in different locations, in descending order of priority:

  1. In the current working directory
  2. In the user’s home directory
  3. In the R home directory (R_HOME)

The documentation gives more details.

Since you’ve tried to change the file in locations (2) and (3) without success, it stands to reason that you have another .Renviron file in your current working directory from which you are launching Rscript.

like image 1
Konrad Rudolph Avatar answered Nov 18 '22 18:11

Konrad Rudolph