从朋友列表创建一个简单的非定向朋友图

问题描述:

这是一个简单的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 

注意真正的任务中有数千个节点,每个人的好几个朋友也有几千个,所以我很担心这个表现。我知道这可能是一件容易的事,但不知道从哪里开始。将不胜感激任何帮助。

您也可以尝试

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 

您可以遍历列表中的每个元素,并检查哪些条目在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