【问题标题】:Adding numbers to each node in data.tree向 data.tree 中的每个节点添加数字
【发布时间】:2015-11-01 21:36:41
【问题描述】:

我有以下树:

 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 

【问题讨论】:

  • 嗨@Jaap。如果您使用库(data.tree),您将能够使用示例数据(acme)。它在包装中。

标签: r tree


【解决方案1】:

我们可以使用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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多