Re: [R] setting options only inside functions

From: Hadley Wickham <hadley_at_rice.edu>
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)
  on.exist(close(con))

  force(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) {   open(con)
  on.exist(close(con))

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

  eval(substitute(expr), env)
}

or anonymous functions:

with_connection <- function(con, f) {
  open(con)
  on.exist(close(con))

  f(con)
}

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)

Hadley

-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
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 https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive