Re: [R] setting options only inside functions

From: Hadley Wickham <>
Date: Wed, 27 Apr 2011 16:21:01 -0500

> 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)   force(expr)

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

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

For connections it would be nice to have something like:

with_connection <- function(con, expr) {   open(con)


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) {   open(con)

  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

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 27 Apr 2011 - 21:25:24 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 27 Apr 2011 - 22:00:36 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive