0

I have a list in R looks like, mylist$a, mylist$b, mylist$c, ..., mylist$z. Is there a easier way to combine all those fields of the list into one variable rather then typing a command like cbind(mylist$a,mylist$b,...,mylist$z)?

P.S. All sub-fields has the same dimension.

lolibility
  • 2,187
  • 6
  • 25
  • 45

1 Answers1

4

do.call() calls its first arguments with all the elements in the second argument:

do.call(cbind, mylist)
josliber
  • 43,891
  • 12
  • 98
  • 133
  • can you tell me the difference between this "do.call" and "lapply/sapply" functions. Cause I tried the lapply, but it won't work – lolibility Dec 13 '13 at 21:00
  • 2
    @lolibility `lapply` *apply the same function* to **each** element of a list or here you need to *apply a function* to **all** elements of a list. Another option is to use `Reduce(cbind,mylist)` apply the same function **successively** to each element of a list. – agstudy Dec 13 '13 at 21:08
  • Just to illustrate what agstudy is saying, lapply(mylist, cbind) would return a list. The first element would be cbind(mylist$a), the second element would be cbind(mylist$b), etc. In other words, for your problem this would return back the same thing it was passed, since cbind called with a single argument just returns that argument. On the other hand, do.call(cbind, mylist) is the same as calling cbind(mylist$a, mylist$b, ..., mylist$z) and returning the result of that cbind. – josliber Dec 13 '13 at 21:28
  • @lolibility, Assuming `mylist` has three components, `lapply(mylist, cbind)` is the same as `list(cbind(mylist$a), cbind(mylist$b), cbind(mylist$c))` whereas `do.call(cbind, mylist)` is the same as `cbind(mylist$a, mylist$b, mylist$c)` . – G. Grothendieck Dec 14 '13 at 11:31