I'm trying to link together pairs of unique IDs using R. Given the example below, I have two IDs (here ID1 and ID2) that indicate linkage. I'm trying to create groups of rows that are linked. In this example A is linked to B which is linked to D which is linked to E. Because these are all connected, I want to group them together. Next, there is also X which is linked to both Y and Z. Because these two are also connected, I want to assign them to a single group as well. How can I tackle this using R?
Thanks!
Example data:
ID1 ID2
A B
B D
D E
X Y
X Z
DPUT R representation
structure(list(id1 = structure(c(1L, 2L, 3L, 4L, 4L), .Label = c("A", "B", "D", "X"), class = "factor"), id2 = structure(1:5,.Label = c("B", "D", "E", "Y", "Z"), class = "factor")), .Names = c("id1", "id2"), row.names = c(NA, -5L), class = "data.frame")
Output needed:
ID1 ID2 GROUP
A B 1
B D 1
D E 1
X Y 2
X Z 2
As per mentionned by @Frank in the comments, you can use igraph
:
library(igraph)
idf <- graph.data.frame(df)
clusters(idf)$membership
Which gives:
A B D X E Y Z
1 1 1 2 1 2 2
Should you want to assign the result back to rows of df
:
merge(df, stack(clusters(idf)$membership), by.x = "id1", by.y = "ind", all.x = TRUE)
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