setting options only inside functions
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")):
* 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) {
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/