如何从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
你的问题不是很清楚也不可重复。例如,我不知道你的“邻接数组”是什么意思。
除此之外,假设您有一个文本文件(我在这里称之为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)