如何保存 igraph 对象

How to save an igraph object

我在将数据框写入 csv 文件时遇到问题。

g 看起来像这样

> g
IGRAPH c32bbbf UN-- 12 12 -- 
+ attr: name (v/c)
+ edges from c32bbbf (vertex names):
 [1] 2 --3  3 --1  4 --5  5 --6  4 --6  6 --7  6 --8  6 --9  9 --8  10--11 11--12 10--12

None 以下代码有效

write.table(g,  file = "filename.csv", sep = ";", dec = ",", row.names = FALSE)
write.csv2(membership(cluster_edge_betweenness(g)), "name.csv" , row.names = FALSE)
write.table(membership(cluster_edge_betweenness(g)),  file = "name.csv", sep = ";", dec = ",", row.names = FALSE)

显示这个错误

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  cannot coerce class ‘"membership"’ to a data.frame

如何将 g 或 membership(cluster_edge_betweenness(g)) 写入 .csv 文件? 预先感谢您的帮助。

使用 igraph 的 write_graph() 函数。查看可用格式的文档。

write.tablewrite.csv 要求输入是表格数据 (data.frame/matrix/etc.)。您的对象 g 是一个 igraph 对象。正如其他人所提到的,一种选择是使用 igraph 的 write_graph() function,它将图形写入文本文件并允许不同格式的数据写入方式。

另一种选择是使用 igraph 的 as_long_data_frame function 将图形对象转换为数据框,然后可以使用 write.csv 将其写入 csv 文件。但是,这需要命名顶点。

例如:

library(igraph)

g <- make_ring(10)

# add names to vertices
vertex_attr(g) <- list(name = LETTERS[1:10])    
vertex_attr(g, "label") <- V(g)$name

as_long_data_frame(g)    

#>  from to from_name from_label to_name to_label
#>     1  2         A          A       B        B
#>     2  3         B          B       C        C
#>     3  4         C          C       D        D
#>     4  5         D          D       E        E
#>     5  6         E          E       F        F
#>     6  7         F          F       G        G
#>     7  8         G          G       H        H
#>     8  9         H          H       I        I
#>     9 10         I          I       J        J
#>     1 10         A          A       J        J