如何提高以下代码的速度?
for (i in 1:nrow(training)){
score[training[i,1],training[i,2],training[i,4]] = training[i,3]
}
Training
是一个包含四列的矩阵。我只想根据上面的公式构建一个值为training[i,3]
的数组。
谢谢!
答案 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]