R 将自定义二维稀疏矩阵转换为网络

R 将自定义二维稀疏矩阵转换为网络,r,graph,type-conversion,sparse-matrix,R,Graph,Type Conversion,Sparse Matrix,我从程序中导出了这样一个数组,如下所示: 1 2:1.827411e-02 3:5.355330e-02 4:1.827411e-02 5:1.827411e-02 2 1:1.827411e-02 3:1.903553e-02 4:4.568528e-03 5:4.568528e-03 3 1:5.355330e-02 2:1.903553e-02 4:1.903553e-02 5:1.903553e-02 6:7.461929e-02 11:3.350254e-02 4 1:1.827411

我从程序中导出了这样一个数组,如下所示:

1 2:1.827411e-02 3:5.355330e-02 4:1.827411e-02 5:1.827411e-02
2 1:1.827411e-02 3:1.903553e-02 4:4.568528e-03 5:4.568528e-03
3 1:5.355330e-02 2:1.903553e-02 4:1.903553e-02 5:1.903553e-02 6:7.461929e-02 11:3.350254e-02
4 1:1.827411e-02 2:4.568528e-03 3:1.903553e-02 5:4.568528e-03
5 1:1.827411e-02 2:4.568528e-03 3:1.903553e-02 4:4.568528e-03
6 3:7.461929e-02 7:1.903553e-02 8:1.903553e-02 9:5.355330e-02 10:1.903553e-02 11:3.350254e-02
7 6:1.903553e-02 8:4.568528e-03 9:1.827411e-02 10:4.568528e-03
8 6:1.903553e-02 7:4.568528e-03 9:1.827411e-02 10:4.568528e-03
9 6:5.355330e-02 7:1.827411e-02 8:1.827411e-02 10:1.827411e-02
10 6:1.903553e-02 7:4.568528e-03 8:4.568528e-03 9:1.827411e-02
11 3:3.350254e-02 6:3.350254e-02
每行描述行的第一个数字和冒号符号前的数字之间的边的权重(冒号符号后)

i、 e第一行:

the weight between 1 and 2 is 1.827411e-02
the weight between 1 and 3 is 5.355330e-02
the weight between 1 and 4 is 1.827411e-02
the weight between 1 and 5 is 1.827411e-02
接下来的几行就是如此


这个信息我想把它转换成一个igraph或网络元素来做更多的分析。有什么有效的方法可以做到这一点吗

您可以使用一个小正则表达式来提取相关值以形成加权边列表

# parent node : grab the first number
parent <- sub("(\\d+ ).*$", "\\1", r) 

# child node: grab everything after the first number and split it
child <- strsplit(sub("\\d+ (.*$)", "\\1", r), ":| ")

# cbind the parent node to the child    
dat2 <- cbind(rep(parent, lengths(child)/2), matrix(unlist(child), nc=2, byrow=TRUE))

mode(dat2) = "numeric" # change to numeric


# read in a graph: the weights are in the edge attributes
g <- igraph::graph_from_data_frame(dat2)

非常感谢你的回答。你知道如何在绘图时考虑权重吗?我使用了
plot.igraph(g,edge.width=E(g)$weight)
并且似乎没有改变边的宽度。由于权重相似,您可能不会看到太多差异。你可以重新缩放ie
E(g)$weight2
txt <- 
  '1 2:1.827411e-02 3:5.355330e-02 4:1.827411e-02 5:1.827411e-02
2 1:1.827411e-02 3:1.903553e-02 4:4.568528e-03 5:4.568528e-03
3 1:5.355330e-02 2:1.903553e-02 4:1.903553e-02 5:1.903553e-02 6:7.461929e-02 11:3.350254e-02
4 1:1.827411e-02 2:4.568528e-03 3:1.903553e-02 5:4.568528e-03
5 1:1.827411e-02 2:4.568528e-03 3:1.903553e-02 4:4.568528e-03
6 3:7.461929e-02 7:1.903553e-02 8:1.903553e-02 9:5.355330e-02 10:1.903553e-02 11:3.350254e-02
7 6:1.903553e-02 8:4.568528e-03 9:1.827411e-02 10:4.568528e-03
8 6:1.903553e-02 7:4.568528e-03 9:1.827411e-02 10:4.568528e-03
9 6:5.355330e-02 7:1.827411e-02 8:1.827411e-02 10:1.827411e-02
10 6:1.903553e-02 7:4.568528e-03 8:4.568528e-03 9:1.827411e-02
11 3:3.350254e-02 6:3.350254e-02'

r <- readLines(textConnection(txt))