r从邻接表创建邻接矩阵或边列表 [英] r create adjacency matrix or edge list from adjacency list

查看:295
本文介绍了r从邻接表创建邻接矩阵或边列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个邻接列表,我正在尝试使其成为邻接矩阵或边缘列表.这是为了对从邻接矩阵或边缘列表建立的网络进行网络分析.我正在使用R. 邻接表的示例如下(每行条目数量不同,空条目为NA)

I have an adjacency list and I am trying to make it into and adjacency matrix or edge list. This is in order to conduct network analysis on the network built from the adjacency matrix or edge list. I am using R. An example of adjacency list is as follows (each row has different amount of entries, and the empty entries are NA):

[17,50,90,NA,NA;
80,67,NA,NA,NA;
33,31,32, NA,NA;
33,31,32,NA,NA;
354,56,87,97,32;
....]

我尝试使用 R:邻接列表到邻接矩阵,但这仅如果我的邻接列表有两个条目(即,一个组中有两个以上的邻居),则可以使用.我得到一个边缘列表,但只考虑了列表中的前两个条目.

I tried using R: Adjacency list to Adjacency matrix but this only works if my adjacency list has two entries (ie there are more than two neighbors in a group). I get an edge list but only taking into account the first two entries in my list.

我还尝试使用从列表到邻接矩阵,但使用igraphmake_graph(unlist(mydata))导致错误:"At type_indexededgelist.c:117 : cannot create empty graph with negative number of vertices, Invalid value"

I also tried using From list to adjacency matrix but using igraph and make_graph(unlist(mydata)) led to the error: "At type_indexededgelist.c:117 : cannot create empty graph with negative number of vertices, Invalid value"

我需要一个邻接矩阵,该矩阵考虑网络中的权重(例如,如果条目31和32位于两行中,则它们的边缘权重将为2). 谢谢您的帮助.

I need an adjacency matrix which takes into account the weights that would be in the network (like if entry 31 and 32 are in two rows, then their edge weight would be 2). Thank you for any help.

推荐答案

我有一个邻接列表,我正在尝试将其放入边缘列表.

I have an adjacency list and I am trying to make it into an[...] edge list.

也许你可以做

lst <- read.csv(header=F, comment.char=";", colClasses="integer", text="
17,50,90,NA,NA;
80,67,NA,NA,NA;
33,31,32,NA,NA;
33,31,32,NA,NA;
354,56,87,97,32;")
m <- as.matrix(lst)
e <- stack(split(m, row(m)))[,2:1]
(e <- e[complete.cases(e),])
# 1    1     17
# 2    1     50
# 3    1     90
# 6    2     80
# 7    2     67
# 11   3     33
# 12   3     31
# 13   3     32
# 16   4     33
# 17   4     31
# 18   4     32
# 21   5    354
# 22   5     56
# 23   5     87
# 24   5     97
# 25   5     32

e <- apply(lst, 1, function(x)x[!is.na(x)])
(e <- do.call(rbind, lapply(e, embed, 2))[,2:1])
#      [,1] [,2]
# [1,]   17   50
# [2,]   50   90
# [3,]   80   67
# [4,]   33   31
# [5,]   31   32
# [6,]   33   31
# [7,]   31   32
# [8,]  354   56
# [9,]   56   87
# [10,]   87   97
# [11,]   97   32

取决于您的需求/邻接表"代表什么.

depending on what you need/what your "adjacency list" represents.

这篇关于r从邻接表创建邻接矩阵或边列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆