【发布时间】:2021-09-24 12:39:51
【问题描述】:
【问题讨论】:
【问题讨论】:
library(data.tree)
直接使用名称而不是 data.tree 中的 ID 更容易,因此我们进行自连接以在同一个表中获取父名称。
df <- merge(df, df, by.x = "ParentId", by.y = "Id",
suffixes = c("", ".Parent"))
tree <- FromDataFrameNetwork(df[c("Name.Parent", "Name")])
# levelName
# 1 Biota
# 2 ¦--Plantea
# 3 ¦ ¦--Tree
# 4 ¦ ¦ ¦--Bonsai
# 5 ¦ ¦ °--Apple-Tree
# 6 ¦ °--Flower
# 7 °--Animal
# 8 ¦--Bear
# 9 ¦--Fish
# 10 °--Bird
ToDataFrameTypeCol(tree)
# level_1 level_2 level_3 level_4
# 1 Biota Plantea Tree Bonsai
# 2 Biota Plantea Tree Apple-Tree
# 3 Biota Plantea Flower <NA>
# 4 Biota Animal Bear <NA>
# 5 Biota Animal Fish <NA>
# 6 Biota Animal Bird <NA>
有数据:
df <- tibble::tribble(
~Id, ~Name, ~ParentId,
1, "Biota", NA,
2, "Plantea", 1,
3, "Animal", 1,
4, "Tree", 2,
5, "Flower", 2,
6, "Bear", 3,
7, "Fish", 3,
8, "Bird", 3,
9, "Bonsai", 4,
10, "Apple-Tree", 4,
)
【讨论】: