R中的值赋值

use*_*579 0 r

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

for (i in 1:nrow(training)){
     score[training[i,1],training[i,2],training[i,4]] = training[i,3] 
  }
Run Code Online (Sandbox Code Playgroud)

Training是一个有四列的矩阵.我只想构建一个数值,其值是training[i,3]根据上面的公式.

谢谢!

flo*_*del 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.
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下,for循环可以替换为:

score[training[, c(1, 2, 4)]] <- training[, 3]
Run Code Online (Sandbox Code Playgroud)