如何获得按世系相互关联的值的索引列表? [R]

问题描述

假设我有一个数据框,其中有两列指示并行值之间的直接关系。

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

这样:

1 与 2 [1] 相关, 2 与 7 [3] 相关, 7 与 8 [4]

有关

所以我得到了索引 1,3 和 4 的向量

然后 3 与 5 [2] 相关, 并且 5 与 10 [5]

有关

所以我得到了索引 2 和 5 的向量?

它伤害了我的大脑。

解决方法

这可以使用 igraph 库有效解决:

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

如果组的成员也感兴趣:

split(names(common_ids),common_ids)

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

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

带有 igraph 的选项

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

给予

$`1`
[1] 1 3 4

$`2`
[1] 2 5