Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a function on a matrix to produce a list output

Tags:

list

r

igraph

Y: (as a matrix) (2 x 7 , by row)

6 8, 2 5, 2 10, 4 10, 7 8, 4 9, 1 3

y = c(6, 8, 2, 5, 2 ,10, 4, 10, 7, 8, 4, 9, 1, 3)

Y = t(matrix(y, nrow=2))

output (in a list of grouped elements in order):

6 8 7, 5 2 10 4 9, 1 3

I'm trying to achieve the above output using the function linked in the below that takes two vectors a,b and combines on a common element.

I've tried looping but I get lost in managing the lists and was wondering if there is a smarter way to achieve this output. maybe using lapply?

Any ideas or a way forward on this would be much appreciated.

How to combine two vectors by a common element?

I've tried for(i in 1:length(Y[,1])){ ...variations but get nowhere.

like image 566
B. Jenkins Avatar asked Sep 05 '25 00:09

B. Jenkins


1 Answers

This is a graph theory problem - you can think of each of your values as a node of a graph, and if they occur in the same row then there is an edge connecting the nodes. Your goal is to list the connected components (or clusters).

We can then use the igraph package to do the work:

components = Y |> graph_from_edgelist() |> components() |> groups()
# $`1`
# [1] 1 3
#
# $`2`
# [1]  2  4  5  9 10
#
# $`3`
# [1] 6 7 8
like image 182
Gregor Thomas Avatar answered Sep 07 '25 23:09

Gregor Thomas