[R] list assignment syntax?

Gabor Grothendieck ggrothendieck at gmail.com
Sat Mar 31 02:03:46 CEST 2012


On Fri, Mar 30, 2012 at 6:40 PM, ivo welch <ivowel at gmail.com> wrote:
> Dear R wizards:  is there a clean way to assign to elements in a list?
>  what I would like to do, in pseudo R+perl notation is
>
>  f <- function(a,b) list(a+b,a-b)
>  (c,d) <- f(1,2)
>
> and have c be assigned 1+2 and d be assigned 1-2.  right now, I use the clunky
>
>  x <- f(1,2)
>  c <- x[[1]]
>  d <- x[[2]]

Suppose for concreteness that we want to add the first component of
the result to twice the second component of the result.  Also lets
name the components c and d.  Then here are 4 approaches:

f <- function(a,b) list(c = a + b, d = a - b)

# 1
x <- f(1, 2)
x[[1]]  + 2 * x[[2]]

# 2
with( f(1, 2), c + 2 * d )

# 3
attach( f(1, 2))
c + 2*d
detach()

# 4
Using
https://stat.ethz.ch/pipermail/r-help/2004-June/053343.html

list[c, d] <- f(1, 2)
c + 2 * d

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list