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

Create a simple non-directed friends graph from list of friends

这是一个简单的 R 任务。我有一些有 ID 的人的列表和每个人的朋友列表(也有 ID)。他们在这里:

> 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)

我想从这些列表中提取朋友关系来构建朋友网络。为此,我需要创建一个 NxN 矩阵,其中 N - 人数,单元格 (i,j) 中的 0 表示人 i 不是人 j 的朋友,反之亦然(单元格 j, i,在这种情况下,也包含 0)。如果他们是朋友(在人 j 的朋友列表中有人 i 的 ID,反之亦然),该单元格将包含 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

注意真实任务中的节点数是几千个,每个人的好友数也是几千个,所以比较担心性能问题。我知道这可能是一件容易的事,但不知道从哪里开始。非常感谢任何帮助。

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

你也可以试试

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