1

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?

Henrik
  • 65,555
  • 14
  • 143
  • 159
  • You'd like to find all the loops from the data frame to show "them". What is them? Please be more specific. Are you hoping to find matches between your columns? Are you looking for those combinations within each column? This is too difficult without more details. – SharpSharpLes Jan 31 '20 at 03:06
  • @SharpSharpLes Hi, I'd just want to find all cycles from the data frame !! All cycles are listed in bold. But I have no idea hoe to use code to find !! – Chen Hobbit Jan 31 '20 at 03:11
  • 1
    see https://stackoverflow.com/questions/55091438/r-igraph-find-all-cycles – chinsoon12 Jan 31 '20 at 03:15

1 Answers1

4

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

chinsoon12
  • 25,005
  • 4
  • 25
  • 35