I have some graph data stored in a data.table that describe the transitions between some nodes such as:
lfs = data.table( from = c(NA, 'x', 'x', 'y'), to = c('x', 'y', 'p', 'z'), level = 0)
lfs
# from to level
#: NA x 0
#: x y 0
#: x p 0
#: y z 0
I want to find the distance of each node from the start node NA. The expected result is as follows:
# from to level
#: NA x 1
#: x y 2
#: x p 2
#: y z 3
I can solve this problem in a very cumbersome way as follows:
lfs[ is.na(lfs$from) ]$level = 1
target = lfs$from %in% (lfs[ lfs$level == 1 ]$to)
lfs[target]$level = 2
target = lfs$from %in% (lfs[ lfs$level == 2 ]$to)
lfs[target]$level = 3
I guess there should be easier and more generic solutions most probably by using graph manipulation functions in graph libraries such as igraph but I don't know them very well and I don't know what to search for in these libraries specifically.
How can I get the expected output using graph algorithms or do you think of any other easier solutions?