从成对矩阵到Cytoscape边缘表的转换太慢

时间:2019-03-08 05:19:52

标签: r sparse-matrix cytoscape

我的代码类似于this。 给定这样的矩阵:

  a  b  c  d
a 1  NA 3  4
b NA 2  NA 4
c NA NA NA NA
d NA NA NA 4

将其转换为此:

a  a  1
a  c  3
a  d  4
b  b  2
b  d  4
d  d  4

相关代码如下:

  2 pears <- read.delim("pears.txt", header = TRUE, sep = "\t", dec = ".")
  3 edges <- NULL
  4 for (i in 1:nrow(pears)) {
  5         for (j in 1:ncol(pears)) {
  6                 if (!(is.na(pears[i,j]))) {
  7                         edges <- rbind(edges, c(rownames(pears)[i], colnames(pears)[j], pears[i,j]))
  8                 }
  9         }
 10         print(i)
 11 }
 12 colnames(edges) <- c("gene1", "gene2", "PCC")
 13 write.table(edges, "edges.txt", row.names = FALSE, quote = FALSE, sep = "\t")

当我在17804x17804稀疏(99%NA)矩阵上使用screen -S在后​​台从远程服务器运行代码时,它最初每13秒运行5条打印语句。但是,现在它已降低到每分钟7条打印语句。为什么算法随着进展而变得越来越慢?有没有其他方法可以更快地将矩阵转换为Cytoscape的格式?

1 个答案:

答案 0 :(得分:1)

我们将data.frame转换为matrix,使用melt中的reshape2将暗名作为两列,并将值作为第三列,然后在subset使用na.rm删除NA行

library(reshape2)
melt(as.matrix(df1), na.rm = TRUE)

数据

df1 <- structure(list(a = c(1L, NA, NA, NA), b = c(NA, 2L, NA, NA), 
c = c(3L, NA, NA, NA), d = c(4L, 4L, NA, 4L)), class = "data.frame", 
  row.names = c("a", 
  "b", "c", "d"))