How to vectorize nested for-loops when column j is

2019-07-11 01:51发布

问题:

I am trying to vectorize my code and need some help.

Here is a dummy example.

a <- c(0, 0, 0)
b <- c(0, 0, 0)
c <- c(0, 0, 0)

rm <- c(1, 2, 3)
var1 <- c(100, 101, 102)
var2 <- c(200, 201, 202)
var3 <- c(300, 301, 302)

mat <- data.matrix(cbind(a, b, c, rm, var1, var2, var3))

num <- 3

for (i in 1:num) {
  for (j in 1:num) {
    mat[i, j] <- mat[i, 1+num+ mat[j, "rm"]] 
  }
}