【问题标题】:Populating a sparse matrix in R在 R 中填充稀疏矩阵
【发布时间】:2015-10-29 03:26:15
【问题描述】:

我在 R 中填充了一个稀疏矩阵,并在 for 循环中编写了更新,但希望获得一些指针以使其更快。下面是一些示例代码:

library(Matrix)

rowId <- rep(c(101:105), 2)
colId <- rep(c("A", "B"), 5)
count <- 1:10

data <- data.frame(as.character(rowId), colId, count)
names(data) <- c("rowId", "colId", "count")

sparse <- Matrix(nrow = 5, ncol=2, byrow=TRUE, 
                  dimnames = list(unique(rowId), unique(colId)))

for (i in 1:nrow(data)) {
  sparse[data$rowId[i], data$colId[i]] <- data$count[i]
}

有没有更好的方法来更新稀疏矩阵?在我的现实世界问题中,数据有大约 100 万个观察值,稀疏为 25000x38242,顺序运行需要几个小时。

谢谢

斯图尔特

【问题讨论】:

标签: r sparse-matrix


【解决方案1】:

因此,填充稀疏矩阵的链接需要为行/列值传入 2 个向量。所以我这个数据框和它的工作原理:

library(Matrix)

rowId <- rep(c(101:105), 2)
colId <- rep(c("A", "B"), 5)
count <- 1:10

rowIndex <- as.factor(rowId)
colIndex <- as.factor(colId)
rowIndex <- as.numeric(rowIndex)
colIndex <- as.numeric(colIndex)

data <- data.frame(rowIndex, rowId, colIndex, colId, count)

sparse <- sparseMatrix(i=data$rowIndex, j=data$colIndex, x=data$count,
                       dimnames = list(unique(rowId), unique(colId)))

【讨论】:

    【解决方案2】:

    你快到了!实际上,您可以使用表中的数据作为矩阵中的索引在一行中执行此操作:

    sparse[data$rowId,data$colId]<-data$count
    sparse
    5 x 2 Matrix of class "dgeMatrix"
         A  B
    101  6  6
    102  7  7
    103  8  8
    104  9  9
    105 10 10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2013-07-23
      • 2012-07-28
      • 2023-04-05
      • 2023-04-06
      • 1970-01-01
      • 2016-03-14
      相关资源
      最近更新 更多