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

Peng Yu pengyu.ut at gmail.com
Wed Feb 3 20:37:06 CET 2010

```On Wed, Feb 3, 2010 at 12:29 PM, Steve Lianoglou
<mailinglist.honeypot at gmail.com> wrote:
> Hi,
>
> On Wed, Feb 3, 2010 at 1:19 PM, Peng Yu <pengyu.ut at gmail.com> wrote:
>> Suppose that I have the following list of lists of frames 'root'
>> (let's call it a 'tree' of frames). I want to flatten it to be a list
>> of frames. However, if I unlist(root), it will flatten the frames as
>> well. Is there a simply way to flatten the tree to certain depth?
>>
>> aframe1=data.frame(x=1:3,y=1:3)
>> aframe2=data.frame(u=7:9,v=11:13)
>> aframe3=data.frame(p=3:5,q=6:8)
>>
>> main1=list(sub1=aframe1, sub2=aframe2)
>> main2=list(sub3=aframe3)
>>
>> root=list(main1=main1, main2=main2)
>>
>> str(root)
>> unlist(root)
>
> Does `unlist(root, recursive=FALSE)` get you what you want?
>
> R> unlist(root, recursive=FALSE)
> \$main1.sub1
>  x y
> 1 1 1
> 2 2 2
> 3 3 3
>
> \$main1.sub2
>  u  v
> 1 7 11
> 2 8 12
> 3 9 13
>
> \$main2.sub3
>  p q
> 1 3 6
> 2 4 7
> 3 5 8

My example has only 2 levels.

But my questions is not limited to a particular level. The
nonrecursive version flatten the first level. But what if the tree is
of n level and I want to flatten it to m levels (where m < n)?

```