如何根据满足的两个条件之一创建列/索引(以在同一数据帧内实现匹配对的聚类)? [英] How to create a column/index based on either of two conditions being met (to enable clustering of matched pairs within same dataframe)?

查看:79
本文介绍了如何根据满足的两个条件之一创建列/索引(以在同一数据帧内实现匹配对的聚类)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的匹配对(id1和id2)数据集,并希望创建一个索引变量,使我能够将这些对合并为行。

I have a large dataset of matched pairs (id1 and id2) and would like to create an index variable to enable me to merge these pairs into rows.

这样,第一行将是索引1,从那以后索引将增加1,除非id1或id2与上一行中的任何值匹配。在这种情况下,应使用先前归属的索引。

As such, the first row would be index 1 and from then on the index will increase by 1, unless either id1 or id2 match any of the values in previous rows. Where this is the case, the previously attributed index should be applied.

我已经找了好几个星期了,大多数解决方案似乎都无法满足我的需求。

I have looked for weeks and most solutions seem to fall short of what I need.

这里有一些数据可以复制我的内容:

Here's some data to replicate what I have:

id1 <- c(1,2,2,4,6,7,9,11)
id2 <- c(2,3,4,5,7,8,10,2)
df <- cbind(id1,id2)
df <- as.data.frame(df)

df
  id1 id2
1   1   2
2   2   3
3   2   4
4   4   5
5   6   7
6   7   8
7   9  10
8  11   2

这是希望实现的目标:

#wanted result
index <- c(1,1,1,1,2,2,3,1)
df_indexed <- cbind(df,index)

df_indexed
  id1 id2 index
1   1   2     1
2   2   3     1
3   2   4     1
4   4   5     1
5   6   7     2
6   7   8     2
7   9  10     3
8  11   2     1


推荐答案

igraph

library(igraph)
g <- graph.data.frame(df)
df$index <- clusters(g)$membership[as.character(df$id1)]
df$index
#[1] 1 1 1 1 2 2 3 1

这篇关于如何根据满足的两个条件之一创建列/索引(以在同一数据帧内实现匹配对的聚类)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆