我在R中创建了一个邻接矩阵,其源文件是这样的:
Gene1 Gene2 Weight
A B 1
A C 0.5
B D -0.5
A D -1
这是我的R代码:
el=read.csv("~/my.csv", sep="\t")
library(igraph)
g = graph.data.frame(el)
adj = as_adj(g, attr='Weight')
以上代码正常运行,下面是邻接矩阵。
> adj
4 x 4 sparse Matrix of class "dgCMatrix"
A B C D
A . 1 0.5 -1.0
B . . . -0.5
C . . . .
D . . . .
我可以帮您将这个邻接矩阵导出为CSV文件吗?我一直在尝试使用代码
write.table
,但是一直无法成功。例如:
> write.table(adj, file="~/matrix.txt", row.names=FALSE, col.names=FALSE)
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class "structure("dgCMatrix", package = "Matrix")" to a data.frame