如何从带有边符号(v,w)的.txt格式的文件导入邻接数组?

问题描述 投票:-3回答:1

如何从RStudio中带有边符号(v,w)的.txt格式的文件导入邻接数组?

.txt文件的内容如下:

5vertices,não dirigido
0,1
1,2
1,3
2,3
3,4
4,0
Reinforcement that this is the notation of vertices in the format (v, w).
vertices: 0 to 4
r igraph adjacency-matrix edges
1个回答
0
投票

你的问题不是很清楚也不可重复。例如,我不知道你的“邻接数组”是什么意思。

除此之外,假设您有一个文本文件(我在这里称之为sample.txt),其中包含以下内容

5vertices,não dirigido
0,1
1,2
1,3
2,3
3,4
4,0
Reinforcement that this is the notation of vertices in the format (v, w).
vertices: 0 to 4

你可以使用readLines逐行读取文件,提取边列表并创建一个igraph对象:

ln <- readLines("sample.txt")

# Store as matrix with from/to indices
vtx <- do.call(rbind, strsplit(ln[grep("\\d+,\\d+", ln)], ","))

# Convert indices to integer and convert to igraph
library(igraph)
ig <- graph_from_data_frame(apply(vtx, 2, as.integer))

plot(ig)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.