Find all cycles in data

前端 未结 1 516
无人共我
无人共我 2021-01-24 09:13

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\'         


        
1条回答
  •  北海茫月
    2021-01-24 10:15

    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

    0 讨论(0)
提交回复
热议问题