如何提高以下代码的速度?
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]根据上面的公式.
谢谢!
您可以使用矩阵进行索引.以下是[文档的相关部分:
Run Code Online (Sandbox Code Playgroud)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]
Run Code Online (Sandbox Code Playgroud)