2015-09-12 151 views
2

我有一個具有5000行和4000列的零矩陣。 另外,我還有另外一個有400,000行和3列的矩陣。第一列表示行索引,第二列表示列索引,最後一列是值。 我想用索引矩陣更新第一個矩陣。 例如:使用R中的索引矩陣更新矩陣

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 

什麼是我的大問題的最佳/有效的解決方案?

回答

4

由於您始終可以使用兩列矩陣進行索引,因此可以將前兩列用作完整索引,然後用第三列替換。

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