Home > Enterprise >  Tidyverse way of repeatedly following parent IDs until ancestor
Tidyverse way of repeatedly following parent IDs until ancestor

Time:12-31

enter image description here

# get startpoints (which are endpoints in your case)
startpoints <- names(V(g)[degree(g, mode = 'out') > 0 & degree(g, mode = 'in') == 0])
#[1] "206" "301" "209" "210"

#calculate all paths from all startpoints
l <- unlist(lapply(startpoints , function(x) all_simple_paths(g, from=x)), recursive = FALSE)
# get the nodes involved.. the first node is the 'parent'/starting point
ans <- lapply(seq.int(l), function(i) as_ids(l[[i]]))
# [[1]]
# [1] "206" "207"
# [[2]]
# [1] "206" "207" "208"
# [[3]]
# [1] "301" "302"
# [[4]]
# [1] "209" "208"
# [[5]]
# [1] "210" "207"
# [[6]]
# [1] "210" "207" "208"

unique(
  bind_rows(
    lapply(ans, function(x) data.frame(parent = x[1], child = x[2:length(x)]))
  ))

#   parent child
# 1    206   207
# 3    206   208
# 4    301   302
# 5    209   208
# 6    210   207
# 8    210   208

This information, you can join back into your original data

  • Related