0

I have the following 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 

I would like to enumerate the tree nodes name by adding the number of line to each node name as followed:

> 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 
Avi
  • 2,247
  • 4
  • 30
  • 52
  • 1
    Please give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap Nov 01 '15 at 10:25
  • 1
    Hi @Jaap. If you use library (data.tree) you will be able to use the example data(acme). It is in the package. – Avi Nov 01 '15 at 10:30

1 Answers1

7

We could use Get to traverse the tree, collect the name and concatenate (paste0) from 1 to totalCount along the way. Then use Set to traverse the tree and assign value:

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

Which gives:

#                        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 
Steven Beaupré
  • 21,343
  • 7
  • 57
  • 77