How can I get a list of indices of values related to each other by lineage? [R]

Viewed 43

suppose I have a dataframe where there are two columns that indicate a direct relationship between the parallel values.

c2 <- c(2,5,7,8,10)
c1 <- c(1,3,2,7,5)
df <- data.frame(c1, c2)

Such that:

1 is related to 2 [1], 2 is related to 7 [3], 7 is related to 8 [4]

So I get a vector of the indexes 1,3, and 4

and then 3 is related to 5 [2], and 5 is related to 10 [5]

so I get a vector of the indexes 2 and 5?

It hurts my brain.

2 Answers

This could be effectively solved using the igraph library:

common_ids <- clusters(graph_from_data_frame(df, directed = FALSE))$membership
split(1:nrow(df), common_ids[match(df$c1, names(common_ids))])

$`1`
[1] 1 3 4

$`2`
[1] 2 5

If also members of the groups are of interest:

split(names(common_ids), common_ids)

$`1`
[1] "1" "2" "7" "8"

$`2`
[1] "3"  "5"  "10"

An option with igraph

lapply(
  groups(components(graph_from_data_frame(df, directed = FALSE))),
  function(x) Filter(Negate(is.na),match(x, as.character(df$c1)))
)

gives

$`1`
[1] 1 3 4

$`2`
[1] 2 5
Related