[R] getOption() versus Sys.getenv

Duncan Murdoch murdoch.duncan at gmail.com
Fri Aug 25 19:33:40 CEST 2017


On 25/08/2017 1:19 PM, Sam Albers wrote:
> Hi there,
> 
> I am trying to distinguish between getOption() and Sys.getenv(). My
> understanding is that these are both used to set values for variables.
> getOption is set something like this: option("var" = "A"). This can be
> placed in an .Rprofile or at the top of script. They are called like this
> getOption("var").
> 
> Environmental variables are set in the .Renviron file like this: "var" =
> "A" and called like this: Sys.getenv("var"). I've seen mention in the httr
> package documentation that credentials for APIs should be stored in this
> way.
> 
> So my question is how does one decide which path is most appropriate? For
> example I am working on a package that has to query a database in almost
> every function call. I want to provide users an ability to skip having to
> specify that path in every function call. So in this case should I
> recommend users store the path as an option or as an environmental
> variable? If I am storing credentials in an .Renviron file then maybe I
> should store the path there as well?
> 
> More generally the question is can anyone recommend some good
> discussion/documentation on this topic?


The environment is set outside of R; it's really part of the operating 
system that runs R.  So use Sys.getenv() if you want the user to be able 
to set something before starting R.  Use Sys.setenv() only if your R 
program is going to use system() (or related function) to run another 
process, and you want to communicate with it.

The options live entirely within a given session.

The .Renviron and .Rprofile files hide this difference, but they aren't 
the only ways to set these things, they're just convenient ways to set 
them at the start of a session.

Duncan Murdoch



More information about the R-help mailing list