Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/66049983/how-can-i-get-a-list-of-indices-of-values-related-to-each-other-by-lineage-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...