[R] <-

David Brahm brahm at alum.mit.edu
Thu May 15 17:32:44 CEST 2003

Damon Wischik <djw1005 at cam.ac.uk> wrote:
> One thing I would find very handy is a shortcut for
>   res <- myfunc()
>   a <- res$val1
>   b <- res$val2
> Something along the lines of
>   list(a=val1,b=val2) <- myfunc()
> but I don't know what the right syntax would be or how I'd go about
> programming it. Any suggestions?

I agree this would be handy!  And appealing to Perl folks who are used to:
  Perl> ($arg1, $arg2) = @ARGV;
I couldn't figure out how to do it with replacement functions (see Prof Brian
Ripley's <ripley at stats.ox.ac.uk> reply), but here's another approach:

multi.assign <- function(x, ...) {
  mycall <- match.call()[-2]
  mycall[1] <- call("list")
  mylist <- eval(mycall, x)
  for (i in names(mylist)) assign(i, mylist[[i]], parent.frame())

Here's an example:
  R> myfunc <- function() list(val1=7, val2=c(5,5))
  R> multi.assign(myfunc(), a=val1, b=val2, d=val1+val2)
  R> a
     [1] 7
  R> b
     [1] 5 5
  R> d
     [1] 12 12
                              -- David Brahm (brahm at alum.mit.edu)

More information about the R-help mailing list