Wednesday, December 3, 2014

R System Environment Variables (SEV)

1. Fix bug of not recognizing pdflatex in Rstudio when using knitr
In R, SEV can be obtained by:
> Sys.getenv()
> Sys.getenv(PATH)
> Sys.setenv(path.to.dropbox="~/Dropbox/")
> Sys.unsetenv(path.to.dropbox)

The first will return a list of all SEV. Some of them are the same, for example in my case there are two SEV with the same name PATH. This cause a bug in knitr that makes Rstudio not recognizing pdflatex. Removing the wrong one fixes the bug.

2. Automate the process of setting working directory in R. For GUI R, one can set system environment as above. For command line R. One can set SEV in bash_profile. E.g.
> vi ~/.bash_profile
> export path.to.dropbox="~/Dropbox/"

Now with this set on both GUI R and command line R. We can set working environment on both by a single command:
setwd(Sys.getenv("path.to.dropbox"))

3. Modifying a .sh file that run R file. An .sh file to help run R file might look like this:
> #!/bin/bash
> export NJOBS_HIGH=200
> R CMD BATCH --no-save RunGlmnet.R RunGlmnet.out

Then inside the RunGlmnet.R file, we can get the variable set outside NJOBS_HIGH as:
> Sys.getenv('NJOBS_HIGH')
Doing this will not save NJOBS_HIGH as a global variable (exists all the time), but only create this variable when running the above .sh script.

Turns out there is some complication. After restarting R, things are back to before. To set things permanently, we have to change ${R_HOME}/etc/Renviron file. Where ${R_HOME} can be obtained from R:
> Sys.getenv("R_HOME")

No comments:

Post a Comment