![](/img/trans.png)
[英]Is there a R function for creating an empty edge list (two-mode) with two vectors?
[英]Converting a two-mode edge list to a one-mode edge list in R
我有一個數據集,看起來像這樣:
Person Team
10 100
11 100
12 100
10 200
11 200
14 200
15 200
我想根據他們在一起的團隊來推斷彼此認識的人。 換句話說,我想創建一個看起來像這樣的數據集:
Person1 Person2 Count
10 11 2
10 12 1
11 12 1
10 14 1
10 15 1
11 14 1
11 15 1
結果數據集捕獲可以根據原始數據集中概述的團隊推斷出的二元關系。 “ Count”變量反映了一個雙聯在一起在一個團隊中的實例數量。 另外,將哪個ID列為Person1對Person2無關緊要,因為這些關系是無向的。
一種選擇:
do.call(rbind,tapply(dat$Person,dat$Team,function(x)t(combn(x,2))))
# [,1] [,2]
# [1,] 10 11
# [2,] 10 12
# [3,] 11 12
# [4,] 11 13
# [5,] 11 14
# [6,] 11 15
# [7,] 13 14
# [8,] 13 15
# [9,] 14 15
我個人會使用指定的程序包(例如igraph package
來執行此操作,但是在這里您可以分兩步進行操作。
res <-
setNames(do.call(rbind.data.frame,
tapply(dat$Person,dat$Team,
function(x)t(combn(x,2)))),
c('Person1','Person2'))
## compute frequencies of each pair and add it to unique version of res
cbind(unique(res),
Count=as.vector(table(paste(res[,'Person1'],res[,'Person2']))))
# Person1 Person2 Count
# 100.1 10 11 2
# 100.2 10 12 1
# 100.3 11 12 1
# 200.2 10 14 1
# 200.3 10 15 1
# 200.4 11 14 1
# 200.5 11 15 1
# 200.6 14 15 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.