我有表示路径的配对值,我希望能够将这些值组合到路径连接的那些路径中。 例如,我有:
x y
1: 1 2
2: 2 3
3: 4 5
4: 12 13
5: 13 14
6: 13 15
7: 13 16
需要将这些组合在一起,使1-2-3,4-5和12-13-14-15-16分开。
理想输出将是这样的表格:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
[2,] 1 1 1 2 2 3 4 5 6 7 8 9 9 9 9 9
是否有一种算法可以在R?
中有效地完成这项工作答案 0 :(得分:3)
感谢@akrun,使用igraph包,它相对简单:
g <- make_graph(c(1,2, 2,3, 4,5, 12,13, 13,14, 13,15, 13,16), directed = FALSE)
cbind(components(g)$membership, seq(1,16))
给出
[,1] [,2]
[1,] 1 1
[2,] 1 2
[3,] 1 3
[4,] 2 4
[5,] 2 5
[6,] 3 6
[7,] 4 7
[8,] 5 8
[9,] 6 9
[10,] 7 10
[11,] 8 11
[12,] 9 12
[13,] 9 13
[14,] 9 14
[15,] 9 15
[16,] 9 16