4

In python it is possible to decompose a list

x=[1,2,3]
a,b,c=x # a=1 b=2 c=3

is it possible to do something similar in R? for example something like:

x=matrix(rnorm(100),10,10)
[u d v]=svd(x)       # instead of u=svd$u d=svd$d  v=svd$v
Donbeo
  • 17,067
  • 37
  • 114
  • 188
  • 3
    FYI this is called a destructuring bind, and there's an nice implementation at https://github.com/crowding/vadr#destructuring-bind – hadley Oct 31 '13 at 12:42

1 Answers1

0

Not without some hackery and fiddly global assignment, and my personal opinion is that this is not a good thing to do.

Why? Well, if the results from svd (to use your example) are returned together there's a good reason they are returned together - they belong together. Once you break it up you lose that relationship. The only win is having fewer characters to type, and that's not one of the things we optimise with programming - readability should win over that.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
  • I agree that implementations in R must be a hack, but it can lead to more readable code - it makes it very natural to (e.g.) implement a swap. – hadley Oct 31 '13 at 12:43
  • I think if you are swapping things then the chances are those things should be in the same structure and then you just do something like: `z[2:1] = z[1:2]` or `z[c("b","a")] = z[c("a","b")]` - for those reasons I don't like using the destructuring bind in python (where it's in the syntax). – Spacedman Oct 31 '13 at 17:25