2016-09-21 24 views
0

我想提取矩陣中的鏈接數字。如何提取R中矩陣中的鏈接數?

問題;

 [,1] [,2] 
[1,] 1 3 
[2,] 2 4 
[3,] 3 5 
[4,] 5 6 
[5,] 4 7 
[6,] 6 8 

例如,如圖3所示,在第一行第二數目,用3在第三行第二列的連接,則圖5和第三行與5峽灣行。連續,5到6〜8。另外,2個在第二行與4連接到7.作爲結果,

[1] 1 3 5 6 8 

[1] 2 4 7 

回答

4

可以檢查igraph包:

library(igraph) 
g <- graph.data.frame(as.data.frame(mat)) # convert the matrix to data frame and graph object 
m <- clusters(g) # calculate the clusters of the graph based on connections 
lapply(split(m$membership, m$membership), names) # split nodes based on their membership 
                # and extract the name of the nodes 

# $`1` 
# [1] "1" "3" "5" "6" "8" 

# $`2` 
# [1] "2" "4" "7" 

數據

# dput(mat) 
# structure(c(1L, 2L, 3L, 5L, 4L, 6L, 3L, 4L, 5L, 6L, 7L, 8L), .Dim = c(6L, 2L))