将数字添加到 data.tree 中的每个节点

Adding numbers to each node in data.tree

我有以下树:

 library (data.tree) 
    data (acme)
    t1<-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 

我想通过向每个节点名称添加行数来枚举树节点名称,如下所示:

> t1
                          levelName
1  Acme Inc._1                       
2   ¦--Accounting_2
3   ¦   ¦--New Software_3
4   ¦   °--New Accounting Standards_4
5   ¦--Research_5                    
6   ¦   ¦--New Product Line_6        
7   ¦   °--New Labs_7      
8   °--IT_8                          
9       ¦--Outsource_9              
10      ¦--Go agile_10             
11      °--Switch to R_11 

我们可以使用 Get 遍历树,收集 name 并沿途连接(paste0)从 1 到 totalCount。然后用Set遍历树并赋值:

acme$Set(name = paste0(acme$Get("name"), "_", 1:acme$totalCount))
print(acme)

给出:

#                        levelName
#1  Acme Inc._1                       
#2   ¦--Accounting_2                  
#3   ¦   ¦--New Software_3            
#4   ¦   °--New Accounting Standards_4
#5   ¦--Research_5                    
#6   ¦   ¦--New Product Line_6        
#7   ¦   °--New Labs_7                
#8   °--IT_8                          
#9       ¦--Outsource_9               
#10      ¦--Go agile_10               
#11      °--Switch to R_11