Home > Blockchain >  Nested for loops in R such that index of the 2nd = index of the 1st 1
Nested for loops in R such that index of the 2nd = index of the 1st 1

Time:10-04

I'm trying to write a nested for loops (i index 1st loop, j index 2nd loop) such that j starts from i 1 and ends at a specific value (the last value of a vector). In particular:

vettore = 1 : 10

for (i in vettore) {
  j = i   1
  for (j in vettore) {
    cat("i: ", i)
    cat("j: ", j, "\n")
    }
}

I need the following behaviour.

Iteration 1 of 1st loop: i = 1, j = 2 up to j = 10

Iteration 2 of 1st loop: i = 2, j = 3 up to j = 10

and so on. How can I do this?

CodePudding user response:

The second loop should start from j but in your code it is still running for every value of vettore. Also it is better to use seq_along or 1:length(vettore) instead of for (i in vettore).

Here is a way to fix it.

vettore = 1 : 10

for (i in seq_along(vettore)) {
  j = i   1
  for (k in j:length(vettore)) {
    cat("i: ", i)
    cat("\tj: ", k, "\n")
  }
}

#i:  1  j:  2 
#i:  1  j:  3 
#i:  1  j:  4 
#i:  1  j:  5 
#i:  1  j:  6 
#i:  1  j:  7 
#i:  1  j:  8 
#i:  1  j:  9 
#i:  1  j:  10 
#i:  2  j:  3 
#i:  2  j:  4 
#i:  2  j:  5 
#...
#...
  • Related