【问题标题】:creating a larger matrix from smaller matrices in R从 R 中的较小矩阵创建更大的矩阵
【发布时间】:2015-11-25 00:13:42
【问题描述】:

我在名为“Disintegration T1”的文件夹中有一系列文本文件,如下所示:

> 1.txt
0   0   0   0   1
1   0   0   0   1
0   1   0   0   1
0   0   0   0   0
1   1   1   1   0
> 2.txt
0   1   1   0   1
0   0   1   1   1
1   1   0   1   1
1   1   1   0   1
0   0   0   0   1
> 3.txt
0   1   1   1
1   0   0   0
0   0   0   0
1   0   0   0

这些文件都是 4X4 或 5X5。它们必须作为矩阵读入,因为数据用于社交网络分析。我的目标是自动化将这些矩阵放入更大矩阵的过程,使这些矩阵彼此直接对角,并且在更大矩阵的空白处输入 0。在这种情况下,最终结果将如下所示:

> mega_matrix
0   0   0   0   1   0   0   0   0   0   0   0   0   0
1   0   0   0   1   0   0   0   0   0   0   0   0   0
0   1   0   0   1   0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   0   0   0   0   0
1   1   1   1   0   0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   1   1   0   1   0   0   0   0
0   0   0   0   0   0   0   1   1   1   0   0   0   0
0   0   0   0   0   1   1   0   1   1   0   0   0   0
0   0   0   0   0   1   1   1   0   1   0   0   0   0
0   0   0   0   0   0   0   0   0   1   0   0   0   0
0   0   0   0   0   0   0   0   0   0   0   1   1   1
0   0   0   0   0   0   0   0   0   0   1   0   0   0
0   0   0   0   0   0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   0   1   0   0   0

谢谢!

【问题讨论】:

  • 这称为块对角矩阵。见Matrix::bdiag ...

标签: r matrix text-files


【解决方案1】:

你想要来自 Matrix 包的bdiag

library(Matrix)
bdiag(matrix1, matrix2, matrix3)

并完成整个目录(感谢 cmets 中的@user20650):

bdiag(lapply(dir(), function(x){as.matrix(read.table(x))}))

【讨论】:

  • 好吧,这看起来像是一个可靠的解决方案;但是,我有数百个文本文件,所以我会在不手动输入每个文本文件的情况下使用它吗?
  • @costebk08:从包含大量文件的目录中自动读取的任务已在 SO 上反复询问和回答。请进行一些搜索,如果失败,请发布您用作问题编辑的搜索词,有人可能会建议更好的策略。
  • @BondedDust 我尝试了以下方法:> megamatrix <- do.call(rbind, lapply(dir(), function(x) bdiag(as.matrix(read.table(x))))) 并收到以下错误:Error: Matrices must have same number of columns in rbind2(..1, r) 矩阵的列数不同,所以我有点卡住了。
  • @user20650 我认为你需要一个 as.matrix :bdiag(lapply(dir(), function(x){as.matrix(read.table(x))}))
  • @user20650 我试过了,它产生了以下结果:Error in as(x, "CsparseMatrix") : no method or default for coercing “data.frame” to “CsparseMatrix” 然后我尝试了:bdiag(lapply(dir(), as.matrix(read.table))) 产生了:Error in as.vector(x, mode) : cannot coerce type 'closure' to vector of type 'any'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多