2017-09-15 114 views
1

這是一個簡單的R任務。我列出了一些身份證的人和每個人的朋友名單(也有身份證)。他們在這裏:從朋友列表創建一個簡單的非定向朋友圖

> dput(friends_of_people) 
structure(list(`7614` = c(1091, 1252, 1827, 34687), `29752` = c(1419, 
1799, 3353, 4665), `33220` = c(143, 297, 436, 52078), `34687` = c(14, 
17, 34, 70, 161, 7614), `52078` = c(58, 66, 99, 184, 33220)), .Names = c("7614", 
"29752", "33220", "34687", "52078")) 
> dput(people) 
c(7614L, 29752L, 33220L, 34687L, 52078L) 

我想從這些列表中提取朋友關係來構建好友網絡。爲此,我需要創建一個N×N矩陣,其中N是人數,0是單元格(i,j),意味着我不是人j的朋友,反之亦然(單元格j,i,在這種情況下,也包含0)。如果他們是朋友(沒有人的ID我的人j和反之亦然好友列表),細胞將包含1 最後的結果應該是這樣的:

> result 
     7614 29752 33220 34687 52078 
7614  0  0  0  1  0 
29752 0  0  0  0  0 
33220 0  0  0  0  1 
34687 1  0  0  0  0 
52078 0  0  1  0  0 

注意真正的任務中有數千個節點,每個人的好幾個朋友也有幾千個,所以我很擔心這個表現。我知道這可能是一件容易的事,但不知道從哪裏開始。將不勝感激任何幫助。

回答

3

您也可以嘗試

edges <- stack(lapply(friends_of_people, intersect, x=people)[as.character(people)]) 
result <- with(edges, table(factor(values, levels=people), factor(ind, levels=people))) 
result 
    #  7614 29752 33220 34687 52078 
    # 7614  0  0  0  1  0 
    # 29752 0  0  0  0  0 
    # 33220 0  0  0  0  1 
    # 34687 1  0  0  0  0 
    # 52078 0  0  1  0  0 
1

您可以遍歷列表中的每個元素,並檢查哪些條目在people中。

# Matrix filled with 0 
# We assume that there's no connection between people 
res <- matrix(0, length(people), length(people)) 
colnames(res) <- rownames(res) <- people 

# For every element in list  
for(i in seq_along(friends_of_people)) { 
    # Which entries overlap with people vector 
    foo <- people %in% friends_of_people[[I]] 
    # Change status 
    res[i, which(foo)] <- 1 
} 

res 

enter image description here

+1

@AlexeyKnorre我編輯我的答案,並擺脫了雙循環的 - 現在更好的性能。 – PoGibas