我知道改进循环已被问过很多次.我们可以应用族函数来改进R中的for循环.
然而,有没有办法改善矩阵的操作,其中这些操作依赖于另一个矩阵?我的意思是这里,我设置为2的元素test基于另一个矩阵index:
for (i in 1:nrow(test)){
test[i,index[i,]] <- 2
} # where index is predetermined matrix
Run Code Online (Sandbox Code Playgroud)
另一个例子是,我test根据另一个矩阵的行中元素的顺序设置值anyMatrix:
for (i in 1:nrow(test)){
test[i,] <- order(anyMatrix[i,])
}
Run Code Online (Sandbox Code Playgroud)
我可以在这里使用lapply或sapply,但是它们会返回一个列表,并且将它转换回矩阵需要相同的时间.
可重复的例子:
test <- matrix(0, nrow = 10, ncol = 10)
set.seed(1234)
index <- matrix(sample.int(10, 10*10, TRUE), 10, 10)
anyMatrix <- matrix(rnorm(10*10), nrow = 10, ncol = 10)
for (i in 1:nrow(test)){
test[i,index[i,]] <- 2
}
for (i in 1:nrow(test)){
test[i,] <- order(anyMatrix[i,])
}
Run Code Online (Sandbox Code Playgroud)