#r #dataframe #transform
Вопрос:
Ответ №1:
library(data.tree)
Проще работать непосредственно с именами , а не с идентификаторами data.tree
, поэтому мы выполняем самостоятельное объединение, чтобы получить имена родителей в одной таблице.
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,
)