0

I have a collection of functions in a file called some_functions.R and saved in a SVN directory in C:\blah1\blah2\Rcodes\some_functions.R . I have several Rprojects which uses this code file. Say a R project is available in the directory C:\blah1\blah2\Rprojects\project1. I can use hard coded path to refer the file and it works.

source("C:/blah1/blah2/Rcodes/some_functions.R")'  

But I would like to set the path as environmental variable.

Looking at How to unfold user and environment variable in R language? and setting the home directory in windows R I add the following line in the RProfile.site file

Sys.setenv(R_CODE_PATH = "C:/blah1/blah2/Rcodes")

and in the project1.Rnw file

source("R_CODE_PATH/some_functions.R")

But the project file can not read the some_functions.R file. I tried with %R_CODE_PATH% without any luck.

Not sure what I'm missing here. Any help is much appreciated.

Community
  • 1
  • 1
ykh
  • 37
  • 6
  • Consider using projects, either in RStudio or RTVS (R Tools for Visual Studio). This will set the R working directory to the project directory, so you don't have to mess with the environment yourself. – Hong Ooi Feb 28 '17 at 23:49
  • @Hong Ooi 3, I'm using RStudio projects but the problem was to linking an external collection of code file in the project file. Since the code file is used in several projects, I don't want to copy it inside every project directory but rather keep it at one place and update/change in one file only. – ykh Feb 28 '17 at 23:55

1 Answers1

1

You retrieve environment variables using Sys.getenv(). Try:

r_code_path <- Sys.getenv("R_CODE_PATH")

Then, for example:

source(paste(r_code_path, "some_functions.R", sep = "/"))

I would use the .Renviron config file to define environment variables. Put it in whatever directory the R command Sys.getenv("HOME") returns and include lines like this:

R_CODE_PATH=C:/blah1/blah2/Rcodes
neilfws
  • 32,751
  • 5
  • 50
  • 63
  • Thanks, it worked! I use _source(paste(Sys.getenv("R_CODE_PATH"),"some_funcitons.R", sep="/"))_ in one go. – ykh Feb 28 '17 at 23:50
  • I tried .Renviron way earlier too without any success. In this second approach does it overwrite the environment path already created? Ahhh.. I was putting the .Renviron file in the wrong directory, my bad. – ykh Feb 28 '17 at 23:58
  • I am not sure about precedence and overwriting; I'd just choose one system and stick with it if it works. – neilfws Mar 01 '17 at 00:00