查找数据中的所有周期 [英] Find all cycles in data
本文介绍了查找数据中的所有周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有'from'和'to'列的数据:
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'))
我想考虑两行或更多行(从相同值开始和结束),确定所有从-到序列。一个简单的例子就是 ABA
:
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
另一个:
# 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
X-Y-W-X
如何找到这样的循环?
推荐答案
这里是另一种选择:
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])
}
}))
输出:
[[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"
参考:
回复:[igraph]帮助-查找周期,作者:加博尔·塞迪(GáborCsárdi)
Re: [igraph] Help - find cycles by Gábor Csárdi
这篇关于查找数据中的所有周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文