Search code examples
rfor-loopvectorization

How to create vector from nested for loops in R?


may I know whether there's a way to print the results out as a vector from this nested for loop?

for(i in 0:3){
  for(j in 1:3){
    print(0.03*(i-1)+exp(-j))
  }
}

Solution

  • Do you mean this?

    i <- rep(0:3, each=3)
    j <- rep(1:3, times=4)
    0.03*(i-1)+exp(-j)
    [1] 0.33787944 0.10533528 0.01978707 0.36787944 0.13533528 0.04978707 0.39787944 0.16533528 0.07978707 0.42787944 0.19533528 0.10978707
    

    R is vectorised, so for simple tasks like this there's no need to use loops.