[R] setting options only inside functions

Hadley Wickham hadley at rice.edu
Wed Apr 27 23:21:01 CEST 2011

> Put together a list and we can see what might make sense.  If we did
> take this on it would be good to think about providing a reasonable
> mechanism for addressing the small flaw in this function as it is
> defined here.

In devtools, I have:

#' Evaluate code in specified locale.
with_locale <- function(locale, expr) {
  cur <- Sys.getlocale(category = "LC_COLLATE")
  on.exit(Sys.setlocale(category = "LC_COLLATE", locale = cur))

  Sys.setlocale(category = "LC_COLLATE", locale = locale)

(Using force here just to be clear about what's going on)

Bill discussed options().  Other ideas (mostly from skimming apropos("set")):

 * graphics devices (i.e. automatic dev.off)
 * working directory (as in the chdir argument to sys.source)
 * environment variables (Sys.setenv/Sys.getenv)
 * time limits (as replacement for transient = T)

For connections it would be nice to have something like:

with_connection <- function(con, expr) {


but it's a little clumsy, because

with_connection(file("myfile.txt"), {do stuff...})

isn't very useful because you have no way to reference the connection
that you're using. Ruby's blocks have arguments which would require
big changes to R's syntax.  One option would to use pronouns:

with_connection <- function(con, expr) {

  env <- new.env(parent = parent.frame()
  env$.it <- con

  eval(substitute(expr), env)

or anonymous functions:

with_connection <- function(con, f) {


Neither of which seems particularly appealing to me.

(I didn't test any of this code, so no guarantees that it works, but
hopefully you see the ideas)


Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University

More information about the R-help mailing list