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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With