[R] How to flatten a tree (based on list) to a certain depth?

Steve Lianoglou mailinglist.honeypot at gmail.com
Wed Feb 3 21:16:50 CET 2010

On Wed, Feb 3, 2010 at 3:01 PM, Peng Yu <pengyu.ut at gmail.com> wrote:
> On Wed, Feb 3, 2010 at 1:47 PM, Bert Gunter <gunter.berton at gene.com> wrote:
>> -- and you didn't read my reply.
> I did. You said to use a loop. I think flatten a tree to a certain
> level shouldn't be done with a loop. Loop is a way used in the
> imperative programming style. Flatten is in the functional programming
> style. I don't think that it is a good idea to mix the two.

Meh ... I want to call that statement "hogwash", but I'll refrain.

> Also, the flatten a tree to a certain level operation should be
> extracted to a well defined function for re-usability. Using a loop is
> a bad idea to enhance re-usability.

I actually wrote a function that does this a while ago,  which I'll
paste below. Note that it uses both a loop and recursion (*gasp* the

You can modify the function to accept accept a "times" parameter, if
you like, that will likely have to be -1'd on each recursive call ...

It's not all that generalized -- in particular I'm looking at the
is(the.list, 'list') test, but it did what I needed it to do at the
time ... perhaps you'll find it helpful.

extractEmbeddedLists <- function(the.list) {
  ## Lifts embedded lists out of a list, and returns you 1 list with
  ## Warning : recursion!
  parsed <- list()
  if (is(the.list, 'list')) {
    for (arg in the.list) {
      parsed <- c(parsed, extractEmbeddedLists(arg))
  } else {
    parsed <- list(the.list)

And for your example:

R> extractEmbeddedLists(root)
  x y
1 1 1
2 2 2
3 3 3

  u  v
1 7 11
2 8 12
3 9 13

  p q
1 3 6
2 4 7
3 5 8


Steve Lianoglou
Graduate Student: Computational Systems Biology
 | Memorial Sloan-Kettering Cancer Center
 | Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact

More information about the R-help mailing list