使用R

时间:2015-09-12 22:19:21

标签: r

我有一个5000行和4000列的零矩阵。 另外,我有另一个有400,000行和3列的矩阵。第一列表示行索引,第二列表示列索引,最后一列表示值。 我想使用索引矩阵更新第一个矩阵。 例如:

data <- matrix(0, 10, 7)

> data
       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    0    0    0    0    0    0    0
 [2,]    0    0    0    0    0    0    0
 [3,]    0    0    0    0    0    0    0
 [4,]    0    0    0    0    0    0    0
 [5,]    0    0    0    0    0    0    0
 [6,]    0    0    0    0    0    0    0
 [7,]    0    0    0    0    0    0    0
 [8,]    0    0    0    0    0    0    0
 [9,]    0    0    0    0    0    0    0
[10,]    0    0    0    0    0    0    0

ind <- matrix(c(1, 2, 5,
            2, 3, 6,
            5, 7, 4,
            5, 6, 16), ncol=3, byrow=T)

> ind
      [,1] [,2] [,3]
[1,]    1    2    5
[2,]    2    3    6
[3,]    5    7    4
[4,]    5    6   16

我希望在更新元素后获得以下矩阵:

> data
       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    0    5    0    0    0    0    0
 [2,]    0    0    6    0    0    0    0
 [3,]    0    0    0    0    0    0    0
 [4,]    0    0    0    0    0    0    0
 [5,]    0    0    0    0    0    16   4
 [6,]    0    0    0    0    0    0    0
 [7,]    0    0    0    0    0    0    0
 [8,]    0    0    0    0    0    0    0
 [9,]    0    0    0    0    0    0    0
[10,]    0    0    0    0    0    0    0

我的大问题中最好/最有效的解决方案是什么?

1 个答案:

答案 0 :(得分:5)

由于您始终可以使用双列矩阵进行索引,因此可以使用前两列作为完整索引,然后替换为第三列。

data[ind[, -3]] <- ind[, 3]

导致

data
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,]    0    5    0    0    0    0    0
# [2,]    0    0    6    0    0    0    0
# [3,]    0    0    0    0    0    0    0
# [4,]    0    0    0    0    0    0    0
# [5,]    0    0    0    0    0   16    4
# [6,]    0    0    0    0    0    0    0
# [7,]    0    0    0    0    0    0    0
# [8,]    0    0    0    0    0    0    0
# [9,]    0    0    0    0    0    0    0
#[10,]    0    0    0    0    0    0    0