Search code examples
ralgorithmic-trading

Why is my For loop skipping steps? R


My For loop seems to be skipping steps when it should go one step at a time.

Simplifying my code:

for(j in 1:5){
  ventana <- spread_real[j + 1: 180 + j]
}

it takes the subset [j+1:180+j] from a vector 'spread_real' and assigns it to the variable 'ventana'.

But once I run the code and j equals 5, ventana gets the subset spread_real[9:190]

Any help would be greatly appreciated since I've been stuck on this for a long time now.


Solution

  • Change j + 1: 180 + j to (j+1):(180+j).

    Your for loop is not skipping any steps, but rather your precedence is wrong; j + 1:180 + j = (j + j) + (1:180) which is not what you want.