gpt4 book ai didi

r - 将多个节点向量合并到边列表中并将它们转换为邻接矩阵

转载 作者:行者123 更新时间:2023-12-02 09:43:01 32 4
gpt4 key购买 nike

我想将多个关系圈(由id列表组成)映射到一个大的邻接矩阵中。我的数据如下所示

circle_1 = c(1, 3, 5)
circle_2 = c(17, 22, 35, 49)
circle_3 = c(2, 9)
circle_4 = c(12, 28, 33)
circle_5 = c(1, 3, 8, 16, 40)

d_mat = matrix(ncol = 2)

for (i in 1:5) {
#extract id from list
dat = get(paste("circle", i, sep="_"))
#convert to edgelist, each pair is unique
dat_t = t(combn(dat, 2))
#rbind edge list together
edge_list <- rbind(d_mat, dat_t)
}

但是,输出 edge_list 仅返回上次迭代 (circle_5) 的边列表,前三个被覆盖。

此外,假设这五个圆圈是从 50 人的一组中绘制的,我如何将这样的边列表的值映射到 50 x 50 邻接矩阵的相应单元格? (我想 igraph 中的 make_graphas_adjacency_matrix 函数应该可以解决问题,但我现在不知道如何实现)

此外,对于重叠成员资格,例如 circle_1circle_5 中的 (1, 3),这意味着 1 和 3 在这个 50 人网络中链接两次。如何聚合此计数频率并将邻接矩阵转换为加权矩阵?

最佳答案

您可以像开始一样通过组合边缘列表然后直接创建矩阵来完成此操作。

circle_1 = c(1, 3, 5)
circle_2 = c(17, 22, 35, 49)
circle_3 = c(2, 9)
circle_4 = c(12, 28, 33)
circle_5 = c(1, 3, 8, 16, 40)

# lets put all the circles in a list for convenience
circles <- list(circle_1, circle_2, circle_3,
circle_4, circle_5)

# we will lapply along the list, get the complete set of
# edges with combn, and then rbind all the resulting
# structures together
edge_list <- do.call(rbind, lapply(circles, function(circ){t(combn(circ, 2))}))

# we convert to a data.frame and set the factor levels
# such that R knows these are nodes from a set of 50 nodes
edge_list <- data.frame(from = factor(edge_list[,1], levels=1:50),
to = factor(edge_list[,2], levels=1:50))
# take a look
head(edge_list)
#> from to
#> 1 1 3
#> 2 1 5
#> 3 3 5
#> 4 17 22
#> 5 17 35
#> 6 17 49
# we can just use table to make the adjacency matrix. R will create
# a row/column for each level of the factor. We look at the first
# 6x6 entries
table(edge_list)[1:6,1:6] # luckily entry (1,3) = 2 as we hoped
#> to
#> from 1 2 3 4 5 6
#> 1 0 0 2 0 1 0
#> 2 0 0 0 0 0 0
#> 3 0 0 0 0 1 0
#> 4 0 0 0 0 0 0
#> 5 0 0 0 0 0 0
#> 6 0 0 0 0 0 0

该邻接矩阵是上三角矩阵。如果您希望邻接矩阵对称,以反射(reflect)无向图,您可以使用 adj.mat[lower.tri(adj.mat)] <- adj.mat[upper.tri(adj.mat)] 将矩阵的上三角形和下三角形设置为相等.

如果您希望矩阵只是二进制(并且不记录不同圆圈中的多个链接),只需通过 ifelse 语句运行它:

# to convert to purely binary
adj.mat <- table(edge_list)
adj.mat.bin <- ifelse(adj.mat>1, 1, adj.mat)
adj.mat.bin[1:6,1:6]
#> to
#> from 1 2 3 4 5 6
#> 1 0 0 1 0 1 0
#> 2 0 0 0 0 0 0
#> 3 0 0 0 0 1 0
#> 4 0 0 0 0 0 0
#> 5 0 0 0 0 0 0
#> 6 0 0 0 0 0 0

reprex package于2018年11月16日创建(v0.2.1)

关于r - 将多个节点向量合并到边列表中并将它们转换为邻接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336813/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com