I have the following, working, code:
test_hierarchie <- tribble(~child, ~parent,
"A", "B",
"B", "C",
"D", "E"
)
test_hierarchie_transformed <- test_hierarchie %>%
left_join(test_hierarchie, by = c("parent" = "child"), suffix = c("", "_grant")) %>%
left_join(test_hierarchie, by = c("parent_grant" = "child"), suffix = c("", "_grant")) %>%
left_join(test_hierarchie, by = c("parent_grant_grant" = "child"), suffix = c("", "_grant")) %>%
left_join(test_hierarchie, by = c("parent_grant_grant_grant" = "child"), suffix = c("", "_grant")) %>%
left_join(test_hierarchie, by = c("parent_grant_grant_grant_grant" = "child"), suffix = c("", "_grant")) %>%
pivot_longer(names_to = "relation", cols = contains("parent"), values_to = "parent") %>%
filter(!is.na(parent))
With result:
# A tibble: 4 x 3
child relation parent
<chr> <chr> <chr>
1 A parent B
2 A parent_grant C
3 B parent C
4 D parent E
This is the desired result, the large amount of left_joins are there because I'm for the real data not sure what is the maximum hierarchy.
My question is: is there a way to do this more succinct and dynamic? Thanks!
EDIT 1: Yes, I do mean 'grand' instead of 'grant', haha EDIT 2: Great solution, exactly what I was looking for! Thanks everyone for pitching in, the other day I was thinking about another project and iGraph does seem very helpful for that.