【问题标题】:R coordinate-value pairs into a sparse matrix将 R 坐标值对转换为稀疏矩阵
【发布时间】:2013-02-23 23:44:32
【问题描述】:

我在将数据集加载到 R 中的稀疏矩阵时遇到问题。我正在使用 Matrix 包。我拥有的数据格式为x y value。例如:

  V1 V2 V3
  1  2  .34
  7  4  .56
  4  5  .62

我想做的相当于

myMatrix[1,2] = .34
myMatrix[7,4] = .56 
myMatrix[4,5] = .62 

以自动化方式。

我想做这样的事情:

myMatrix = Matrix(nrow=numrows, ncol=numcols)
myMatrix[mydata[1:numrows, 1], mydata[1:numrows, 2]] <- mydata[1:numrows, 3]

但是当我需要一个数字矩阵时,这会使我的矩阵成为 lgeMatrix。

我也试过了:

myMatrix = Matrix(nrow=numrows, ncol=numcols)
for(i in 1:numrows){
    myMatrix[mydata[i, 1], mydata[i, 2]] <- mydata[i, 3]
}

这会创建我想要的那种矩阵,但它需要的时间太长(超过 5 分钟)。我知道它有效,因为当我停止它时,我会检查前几个值并且它们是正确的,但最后一个值是 NA。我正在使用具有 247158 个值的 7095 x 5896 矩阵来输入,所以 for 循环是不可能的,除非我只是不耐烦。

我的问题是:在 R 中执行此操作的首选方法是什么?

更新:

我改用sparseMatrix 解决了这个问题:

myMatrix = sparseMatrix(i = mydata[1:numrows,1], j = mydata[1:numrows,2],
                     x = mydata[1:numrows,3])

不明白sparseMatrix在其他post中的用法

【问题讨论】:

标签: r matrix sparse-matrix


【解决方案1】:

假设这是一个名为 dat 的数据框:

myMatrix = Matrix(0, nrow=10, ncol=10)
# Notice that you need to specify zero values to make it sparse.
myMatrix[cbind(dat$V1, dat$V2)] <- dat$V3
myMatrix
#--------------
10 x 10 sparse Matrix of class "dgCMatrix"

 [1,] . 0.34 . .    .    . . . . .
 [2,] . .    . .    .    . . . . .
 [3,] . .    . .    .    . . . . .
 [4,] . .    . .    0.62 . . . . .
 [5,] . .    . .    .    . . . . .
 [6,] . .    . .    .    . . . . .
 [7,] . .    . 0.56 .    . . . . .
 [8,] . .    . .    .    . . . . .
 [9,] . .    . .    .    . . . . .
[10,] . .    . .    .    . . . . .

【讨论】:

    猜你喜欢
    • 2013-06-26
    • 2023-04-10
    • 2021-11-25
    • 2017-07-02
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多