R data.tree枚举层次结构

时间:2017-05-29 11:48:53

标签: r tree hierarchy enumerate

我是data.tree的新手,喜欢用几个维度枚举一个巨大的层次结构。 实际上我正在使用嵌套循环进行拼接和迭代,使用爬升非常糟糕。

library(data.tree)    
for(i2 in 1:2) {
  for(i3 in 1:2) {
  h2 <- acme$Climb(position = c(1,i2))$path
  h3 <- acme$Climb(position = c(1,i2,i3))$path
  print(sprintf("%d.%d.%d",1,i2, i3))
  print(sprintf("%d.%d",1,i2))
 }
 }

1 Acme Inc. 1 2 | - 会计1.1
3 | | - 新软件1.1.1
4 |° - 新会计准则1.1.2
5 | - 研究1.2
6 | | - 新产品系列1.2.1
7 |° - 新实验室1.2.2
8°--IT 1.3
9 | - 外包1.3.1
10 | - 敏捷开始1.3.2
11° - 切换到R 1.3.3

1 个答案:

答案 0 :(得分:2)

我仍然不确定你想要什么。我们试试这个:

library(data.tree)
data(acme)

NodeName <- function(node) {
  if (node$isRoot) "1"
  else paste(NodeName(node$parent), node$position, sep = ".")
}

print(acme, nme = NodeName)

这会产生:

                          levelName   nme
1  Acme Inc.                            1
2   ¦--Accounting                     1.1
3   ¦   ¦--New Software             1.1.1
4   ¦   °--New Accounting Standards 1.1.2
5   ¦--Research                       1.2
6   ¦   ¦--New Product Line         1.2.1
7   ¦   °--New Labs                 1.2.2
8   °--IT                             1.3
9       ¦--Outsource                1.3.1
10      ¦--Go agile                 1.3.2
11      °--Switch to R              1.3.3