迭代包含3000行的大矩阵并计算相关性。 - 跟进!

时间:2010-07-30 21:26:57

标签: r matrix

谢谢Nico!我纠正了小错误后几乎到了那里。在这里,我附上我的剧本:

datamatrix=read.table("ref.txt", sep="\t", header=T, row.names=1)
correl <- NULL
for (i in 1:nrow(datamatrix)) {
   correl <- apply(datamatrix, 1, function(x) {cor(t(datamatrix[, i]))})
   write.table(correl, paste(row.names(datamatrix)[i], ".txt", sep=""))
}

但我担心function(x)部分有问题,似乎是t(datamatrix[i,j]),它将计算任意两行的corr。

实际上我需要遍历矩阵。第一个cor(row01, row02)获得rwo01和row02之间的一个相关性;然后cor(row01, row03)得到row01和rwo03的相关性,......直到row01 row30000之间的相关性。现在我得到了row01的第一列Row01 1.000 Row02 0.012 Row03 0.023 Row04 0.820 Row05 0.165 Row06 0.230 Row07 0.376 Row08 0.870并保存到文件row01.txt。

同样获取Row02 Row01 0.012 Row02 1.000 Row03 0.023 Row04 0.820 Row05 0.165 Row06 0.230 Row07 0.376 Row08 0.870并将其保存到文件row02.txt。

我将获得30000个文件。这是愚蠢的,但这可以跳过内存限制,并且可以很容易地处理特定行的相关性。

1 个答案:

答案 0 :(得分:1)

首先,您的代码是错误的:相关步骤应为:

correl <- apply(datamatrix, 1, function(x) {cor(x,datamatrix[i, ])})

然后,您最好明确关闭连接,否则R可能会打开太多连接。

最后,使用write.table并不能保证您可以轻松地检索数据。你必须自己构建一个表。试试这段代码:

correl <- NULL
XX <- for (i in 1:nrow(datamatrix)) {
   correl <- apply(datamatrix, 1, function(x) {cor(x,datamatrix[i, ])})
   ff <- file(paste(row.names(datamatrix)[i], ".txt", sep=""),open="at")
      write(paste("row","cor"),ff)
      tmp <- paste(names(correl),correl)
      write(tmp, ff,sep="\n")
   }
   close(ff)
}