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.
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)
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
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.
This is what worked for me
path_to_Renviron_file <- "C:/Users/Administrator/Documents/.Renviron"
readRenviron(path_to_Renviron_file)
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:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With