Manish Pathak
Manish Pathak

Reputation: 55

Find direct hierarchical parents of a leaf node in data.tree package in R

I am trying to create a sub tree from a data tree and need to perform further operations on the sub tree.

data(acme)
print(acme)

Acme Inc.                       
2   ¦--Accounting                  
3   ¦   ¦--New Software            
4   ¦   °--New Accounting Standards

5  ¦--  Research                    
6   ¦   ¦--New Product Line        
7   ¦   °--New Labs                
8 |--IT                          
9         |--Outsource               
10       ¦--Go agile                
11       °--Switch to R  

Now I want to create a sub tree corresponding to the leaf node specified in the name variable below:

name<-"New Labs"

Following code gives me the required sub tree:

subtree<-(FindNode(acme, name)$parent)$parent
print (subtree)

Acme Inc.       
2  °--Research    
3      °--New Labs

But I need a code which doesn't require multiple repetition of "$parent" & gives all the parent till the tree root.

Any help on this would be really appreciated .

Thanks

Upvotes: 2

Views: 715

Answers (1)

GGamba
GGamba

Reputation: 13680

The idea is to Prune the initial tree to a new tree.

We can find the path of any Node with the path propriety, and then Prune() the tree Traversing the tree and keeping only the nodes matching the path.

Because Prune() overwrite the initial tree, we should probably Clone() it first.

library(data.tree)
data("acme")

acme
#>                           levelName
#> 1  Acme Inc.                       
#> 2   ¦--Accounting                  
#> 3   ¦   ¦--New Software            
#> 4   ¦   °--New Accounting Standards
#> 5   ¦--Research                    
#> 6   ¦   ¦--New Product Line        
#> 7   ¦   °--New Labs                
#> 8   °--IT                          
#> 9       ¦--Outsource               
#> 10      ¦--Go agile                
#> 11      °--Switch to R

extract_subtree <- function(tree, node_name) {
  new_tree <- Clone(tree)
  initial_node <- FindNode(new_tree, node_name)
  initial_node$path
  Prune(new_tree, prunFun = function(N) N$name %in% initial_node$path)
  return(new_tree)
}

pruned_acme <- extract_subtree(acme, 'New Labs')

pruned_acme
#>          levelName
#> 1 Acme Inc.       
#> 2  °--Research    
#> 3      °--New Labs


acme
#>                           levelName
#> 1  Acme Inc.                       
#> 2   ¦--Accounting                  
#> 3   ¦   ¦--New Software            
#> 4   ¦   °--New Accounting Standards
#> 5   ¦--Research                    
#> 6   ¦   ¦--New Product Line        
#> 7   ¦   °--New Labs                
#> 8   °--IT                          
#> 9       ¦--Outsource               
#> 10      ¦--Go agile                
#> 11      °--Switch to R

Created on 2018-05-23 by the reprex package (v0.2.0).

Upvotes: 1

Related Questions