[R] assigning from multiple return values
Richard A. O'Keefe
ok at cs.otago.ac.nz
Thu Jun 24 06:46:44 CEST 2004
Gabor Grothendieck <ggrothendieck at myway.com> wrote:
fn <- function(x,y) {
assign(as.character(substitute(x)), "zz", sys.frame(-1))
assign(as.character(substitute(y)), 3, sys.frame(-1))
}
fn(a,b) # sets a to "zz" and b to 3
"list2<-" <- function(x,y,value) {
assign(as.character(substitute(y)), value[[2]], sys.frame(-1))
value[[1]]
}
fn <- function()list("zz",3)
a <- 1 # first arg must exist prior to invoking list2. Its value not important.
list2(a,b) <- fn()
There is still another way, which doesn't use substitute, as.character, or
assign. Instead of returning two results, accept an extra argument which
is a function that decides what to do with them.
> f <- function(handler) { handler("zz", 3) }
> f(function(x, y) { a <<- x; b <<- y })
> a
[1] "zz"
> b
[1] 3
> g <- function() {
+ u <- v <- NULL # make it clear these are local to g
+ f(function(x,y) {u <<- x; v <<- y})
+ list(u, v) # see what we got
+ }
> g()
[[1]]
[1] "zz"
[[2]]
[1] 3
Whenever I would have wanted to pass "a variable" to an R function,
this is what I do instead. It works so well that I am still happily
ignorant of how to use substitute(). It's also much more compiler-friendly.
More information about the R-help
mailing list