【发布时间】:2016-10-01 06:21:45
【问题描述】:
我有一个包含 2 列的数据框,如下所示:
id1 <- c(123,456,789,122,345,678,901,126,567,890,001,002,130,122)
id2 <- c(121,122,123,456,125,126,127,678,129,130,131,132,890,987)
df <- cbind(id1,id2)
df
id1 id2
[1,] 123 121
[2,] 456 122
[3,] 789 123
[4,] 122 456
[5,] 345 125
[6,] 678 126
[7,] 901 127
[8,] 126 678
[9,] 567 129
[10,] 890 130
[11,] 1 131
[12,] 2 132
[13,] 130 890
[14,] 122 987
现在我可以计算 id1 和 id2 的组合等于 id2 和 id1 的组合的所有情况并返回它们,如下所示:
forwards<-paste(V1,V2)
backwards<-paste(V2,V1)
#identifying combinations
intersect(forwards, backwards)
[1] "456 122" "122 456" "678 126" "126 678" "890 130" "130 890"
#count combinations
length(intersect(forwards, backwards))
[1] 6
但是现在,对于 id1 仅与 id2 相关且 id2 仅与 id1 相关的所有情况,我想要一个新计数,例如对于 df,该计数将等于 4,因为:
id1==122 is related with id2==456 AND id1==456 is related with id2==122,
but id1 ==122 is too related with id2==987,
因此,新计数应排除这两种情况,并按如下方式计数:
id1 id2
678 126
126 678
890 130
130 890
#count should be equals to 4
我该怎么做?
【问题讨论】: