向 data.tree 中的每个节点添加数字 [英] Adding numbers to each node in data.tree

查看:26
本文介绍了向 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 

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

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 

推荐答案

我们可以使用 Get 来遍历树,收集 name 并连接 (paste0) 从 1 到 totalCount 一路走来.然后使用Set遍历树并赋值:

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)

给出:

#                        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 

这篇关于向 data.tree 中的每个节点添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆