rtree

How to Truncate a data.tree Tree in R to a Specific Level


I'm working with a tree structure in R using the data.tree package. I want to truncate the tree to a specific level, keeping only the nodes up to that level and removing all deeper levels. For example, if I have a tree with 4 levels (root, children, grandchildren, great-grandchildren), I want to truncate it to level 2, keeping only the root, children, and grandchildren.

library(data.tree)

# Create a sample tree
tree <- Node$new("A")
tree$AddChild("B")
tree$AddChild("C")
tree$B$AddChild("D")
tree$B$AddChild("E")
tree$C$AddChild("F")
tree$C$AddChild("G")
tree$B$D$AddChild("H")

print(tree, "name")

I'm looking for a reliable and efficient way to truncate the tree without modifying the original tree structure.

Help!


Solution

  • Use the Clone function:

    Clone(tree, \(x) x$level <= 3) #root, children, and grandchildren.
    
      levelName
    1 A        
    2  ¦--B    
    3  ¦   ¦--D
    4  ¦   °--E
    5  °--C    
    6      ¦--F
    7      °--G
    
    Clone(tree, \(x) x$level <= 2) #root, children
    
      levelName
    1     A    
    2      ¦--B
    3      °--C
    

    If you want to modify the original object, use Prune function with the same logic as above