R 查找数据中的所有周期
我有“从”和“到”列的数据:R 查找数据中的所有周期,r,dataframe,cycle,R,Dataframe,Cycle,我有“从”和“到”列的数据: df = data.frame(from = c('A','A','X','E','B','W','C','Y'), to = c('B','E','Y','C','A','X','A','W')) 我想确定“从到”的所有序列,考虑两行或更多行,它们以相同的值开始和结束。一个简单的方法是A-B-A: # df # from to # 1 A B # 1. From A to B # 2 A E # 3 X
df = data.frame(from = c('A','A','X','E','B','W','C','Y'),
to = c('B','E','Y','C','A','X','A','W'))
我想确定“从到”的所有序列,考虑两行或更多行,它们以相同的值开始和结束。一个简单的方法是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])
}
}))
参考:
Gábor Csárdi这里是另一个选项:
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])
}
}))
参考:
通过Gábor Csárdi您希望找到数据帧中的所有循环以显示“它们”。它们是什么?请说得更具体些。您希望在列之间找到匹配项吗?您是否在每个列中查找这些组合?没有更多细节,这太难了。@Sharples嗨,我只想从数据帧中找到所有周期!!所有周期均以粗体显示。但是我不知道如何使用代码来查找!!请看,您希望从数据框中找到所有循环以显示“它们”。它们是什么?请说得更具体些。您希望在列之间找到匹配项吗?您是否在每个列中查找这些组合?没有更多细节,这太难了。@Sharples嗨,我只想从数据帧中找到所有周期!!所有周期均以粗体显示。但是我不知道如何使用代码来查找!!看见