【发布时间】:2021-10-24 02:42:31
【问题描述】:
我有描述父子关系的数据:
df <- tibble::tribble(
~Child, ~Parent,
"Fruit", "Food",
"Vegetable", "Food",
"Apple", "Fruit",
"Banana", "Fruit",
"Pear", "Fruit",
"Carrot", "Vegetable",
"Celery", "Vegetable",
"Bike", "Not Food",
"Car", "Not Food"
)
df
#> # A tibble: 9 x 2
#> Child Parent
#> <chr> <chr>
#> 1 Fruit Food
#> 2 Vegetable Food
#> 3 Apple Fruit
#> 4 Banana Fruit
#> 5 Pear Fruit
#> 6 Carrot Vegetable
#> 7 Celery Vegetable
#> 8 Bike Not Food
#> 9 Car Not Food
在视觉上,这看起来像:
最终,我想要的结果是将其“展平”为看起来更像这样的结构:
results <- tibble::tribble(
~Level.03, ~Level.02, ~Level.01,
"Apple", "Fruit", "Food",
"Banana", "Fruit", "Food",
"Pear", "Fruit", "Food",
NA, "Bike", "Not Food",
NA, "Car", "Not Food"
)
results
#> # A tibble: 5 x 3
#> Level.03 Level.02 Level.01
#> <chr> <chr> <chr>
#> 1 Apple Fruit Food
#> 2 Banana Fruit Food
#> 3 Pear Fruit Food
#> 4 <NA> Bike Not Food
#> 5 <NA> Car Not Food
注意:并非所有元素都具有所有级别。例如,bike 和 car 没有 Level.03 元素。
我觉得有一种方法可以优雅地使用tidyr 或jsonlite 的某种类型的next/unnest 函数?我从递归连接开始,但我觉得我在重新发明轮子,并且可能有一种直截了当的方法。
【问题讨论】:
-
你是否像树状图一样思考?
-
为什么不使用while循环来解决这个问题?
标签: r tidyr data-manipulation hierarchical-data hierarchical