首页 > 解决方案 > R How to Write Double for Loops and Store Result in a Matrix

问题描述

I would like to store result of X[i,j].

X[i,j] = alpha[i] + beta [j]

I tried writing this double for loop but could not get it to store the result. Appreciate any help here. Thanks!

for (i in length(alpha)) { 
  for (j in length(beta)) {
    Xij <- alpha[i] + beta[j]
    matrix[i,j] <- Xij
  }
}

Edit: Is there a more efficient way to do this? The for loop run is taking a long time as the dataset is huge.

标签: rfor-loop

解决方案


for (i in 1:length(alpha)) { 
  for (j in 1:length(beta)) {
    Xij <- alpha[i] + beta[j]
    matrix[i,j] <- Xij
  }
}

推荐阅读