R中的值赋值

时间:2013-04-26 04:28:29

标签: r

如何提高以下代码的速度?

for (i in 1:nrow(training)){
     score[training[i,1],training[i,2],training[i,4]] = training[i,3] 
  }

Training是一个包含四列的矩阵。我只想根据上面的公式构建一个值为training[i,3]的数组。

谢谢!

1 个答案:

答案 0 :(得分:6)

您可以使用矩阵进行索引。以下是[文档的相关部分:

  
A third form of indexing is via a numeric matrix with the one
 column for each dimension: each row of the index matrix then
 selects a single element of the array, and the result is a vector.
  

因此,在您的情况下,for循环可以替换为:

score[training[, c(1, 2, 4)]] <- training[, 3]