在 R 的 data.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  

现在我想创建一个与下面 name 变量中指定的叶节点对应的子树:

name<-"New Labs"

以下代码为我提供了所需的子树:

subtree<-(FindNode(acme, name)$parent)$parent
print (subtree)
Acme Inc.       
2  °--Research    
3      °--New Labs

但是我需要一个不需要多次重复"$parent"的代码,并给出所有父级直到树根。

对此的任何帮助将不胜感激。

谢谢

这个想法是将初始树Prune为新树。

我们可以找到任何具有path属性的Node的路径,然后Prune()树遍历树并仅保留与路径匹配的节点。

因为Prune()覆盖初始树,所以我们可能应该先Clone()它。

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

创建于 2018-05-23 由 reprex 包 (v0.2.0(.

最新更新