Find all cycles in data

放肆的年华 提交于 2020-07-16 06:45:12

问题


I have data with 'from' and 'to' columns:

df = data.frame(from = c('A','A','X','E','B','W','C','Y'),
                to  = c('B','E','Y','C','A','X','A','W'))

I'd like to identify all sequences of 'from-to', considering two or more rows, which starts and ends on the same value. An easy one would be A-B-A:

# df
#   from to
# 1    A  B # 1. From A to B
# 2    A  E
# 3    X  Y
# 4    E  C
# 5    B  A # 2. From B and back to the starting point A, completing the sequence A-B-A
# 6    W  X
# 7    C  A
# 8    Y  W

Another one:

# df
#   from to
# 1    A  B 
# 2    A  E # 1.
# 3    X  Y
# 4    E  C # 2.
# 5    B  A 
# 6    W  X
# 7    C  A # 3. -> Thus: A - E - C - A
# 8    Y  W

There is also e.g. X - Y - W - X

How can I find such cycles?


回答1:


Here is another option:

library(igraph)
g <- graph_from_data_frame(h)

#https://lists.nongnu.org/archive/html/igraph-help/2009-04/msg00125.html
find.cycles <- function(graph, k) {
    ring <- graph.ring(k, TRUE)
    subgraph_isomorphisms(ring, graph)
}

#find all cycles
N <- length(unique(unlist(h)))
l <- unlist(lapply(1L:N, find.cycles, graph=g), recursive=FALSE)

#extract the vertices in each cycle
Filter(Negate(is.null), lapply(l, function(e) {
    if (length(e) > 1L) {
        nm <- names(e)
        c(nm, nm[1L])
    }
}))

output:

[[1]]
[1] "A" "B" "A"

[[2]]
[1] "B" "A" "B"

[[3]]
[1] "A" "E" "C" "A"

[[4]]
[1] "X" "Y" "W" "X"

[[5]]
[1] "E" "C" "A" "E"

[[6]]
[1] "W" "X" "Y" "W"

[[7]]
[1] "C" "A" "E" "C"

[[8]]
[1] "Y" "W" "X" "Y"

Reference:

Re: [igraph] Help - find cycles by Gábor Csárdi



来源:https://stackoverflow.com/questions/59997320/find-all-cycles-in-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!