Inno
Inno

Reputation: 75

How to extract the chaining numbers in a matrix in R?

I wanna extract the chaining numbers in a matrix.

Problem;

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

For example, 3, second number in first row, is connecting with 3 in third row, then 5 in second column and third row is with 5 in firth row. Consecutively, 5 to 6 to 8. Also, 2 in second row is connecting with 4 to 7. As a results,

[1] 1 3 5 6 8

[1] 2 4 7

Upvotes: 0

Views: 45

Answers (1)

akuiper
akuiper

Reputation: 214927

You can check igraph package:

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"

Data:

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

Upvotes: 4

Related Questions