I have data that describes parent-child relationships:
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
Visually, this looks like:
Ultimately, my desired results are to "flatten" this to a structure that looks more like this:
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
NOTE: Not all of the elements will have all of the levels. For example, bike and car do not have Level.03 elements.
I feel like there's a way to do this elegantly with tidyr or some type of next/unnest function from jsonlite? I started with a recursive join, but I feel like I'm re-inventing the wheel and there's likely a straight-forward approach.
