Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 从成对数据中重建序列_R_Sequence - Fatal编程技术网

R 从成对数据中重建序列

R 从成对数据中重建序列,r,sequence,R,Sequence,我正试图从成对中重建序列,以获得元素a和所有其他元素b、c、d、e之间的最短路径(或所有路径,我也可以使用)。我在R工作。假设我有五双鞋: c("ae","bc","cd","ca","de") pair的元素可以排列,因此bc可以变成cb。我希望在最后有以下四个序列: c("ae") #from a to e c("ac") #from a to c c("ae","ed") #from a to d c("ac","cb") #from a to b 我尝试使用循环和regexp

我正试图从成对中重建序列,以获得元素
a
和所有其他元素
b、c、d、e
之间的最短路径(或所有路径,我也可以使用)。我在R工作。假设我有五双鞋:

c("ae","bc","cd","ca","de")
pair的元素可以排列,因此
bc
可以变成
cb
。我希望在最后有以下四个序列:

c("ae") #from  a to e
c("ac") #from  a to c
c("ae","ed") #from  a to d
c("ac","cb") #from  a to b

我尝试使用循环和
regexpr
来查找特定字母在所有对中的位置,但最终总是遇到如何管理多个组合的问题。我发现这个问题与我的()类似,答案是研究拓扑排序。我已经研究过了,但没有找到如何准确地使用它来解决我的问题。

您可以通过将序列转换为图形边,然后使用IGRAPHE包中的
最短路径来找到路径,从而获得与此等价的结果

library(igraph)
x = c("ae","bc","cd","ca","de")
EdgeList = matrix(unlist(strsplit(x, "")), ncol=2, byrow=TRUE)
g = graph_from_edgelist(EdgeList , directed = FALSE)
shortest_paths(g, "a")$vpath

[[1]]
+ 1/5 vertex, named:
[1] a

[[2]]
+ 2/5 vertices, named:
[1] a e

[[3]]
+ 3/5 vertices, named:
[1] a c b

[[4]]
+ 2/5 vertices, named:
[1] a c

[[5]]
+ 3/5 vertices, named:
[1] a e d

您仍然需要进行一些格式化以获得所请求的表示,但这会提供所需的路径

您可以通过将序列转换为图边,然后使用igraph包中的
最短路径
来查找路径,从而获得与此等价的结果

library(igraph)
x = c("ae","bc","cd","ca","de")
EdgeList = matrix(unlist(strsplit(x, "")), ncol=2, byrow=TRUE)
g = graph_from_edgelist(EdgeList , directed = FALSE)
shortest_paths(g, "a")$vpath

[[1]]
+ 1/5 vertex, named:
[1] a

[[2]]
+ 2/5 vertices, named:
[1] a e

[[3]]
+ 3/5 vertices, named:
[1] a c b

[[4]]
+ 2/5 vertices, named:
[1] a c

[[5]]
+ 3/5 vertices, named:
[1] a e d
您仍然需要进行一些格式化以获得所请求的表示,但这会提供所需的路径