Home > Enterprise >  How to create vector from nested for loops in R?
How to create vector from nested for loops in R?

Time:10-21

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))
  }
}

CodePudding user response:

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.

CodePudding user response:

Since you want to print it as a vector I imagine you only want to print it once, at the end of the for-loop. What you can do is create an empty vector and fill it with more data for every iteration like so:

v <- c()
for(i in 0:3){
  for(j in 1:3){
    v <- c(v, 0.03*(i-1) exp(-j))
  }
}
print(v)

Alternatively you can use rbind() instead of c() to create a 12x1 matrix instead of a vector

CodePudding user response:

Keeping your format intact and without using rbind:

output <- c()
k<- 1

for(i in 0:3){
  for(j in 1:3){
    (0.03*(i-1) exp(-j))-> output[k]
    k<- k 1
  }
}

Which will result in:

> output
 [1] 0.33787944 0.10533528 0.01978707 0.36787944 0.13533528 0.04978707 0.39787944 0.16533528
 [9] 0.07978707 0.42787944 0.19533528 0.10978707
  • Related