Home > OS >  R Floop behavior
R Floop behavior

Time:10-24

Suppose I have the following R loop:

for(i in 1:5){
print(i)
i = i   1
}

This produces the following result:

1
2
3
4
5

Which is weird since I did redefine the index inside the loop.

Why do we see this behavior?

I thought I would see something like the following:

1
3
4
5
6

CodePudding user response:

Assignment to the looping variable i is discarded on the next loop iteration, so i = i 1 has no effect. If you want to change the value of i within the loop, you can use a while loop.

However, your intended output of 1 3 4 5 6 doesn't make sense for a couple of reasons:

  • assignment of i, as already mentioned;
  • why does it not increment every other loop?; and
  • the domain of i, 1:5, is locked in at the first pass of the loop.

Having said that, try this:

i <- 1
lim <- 5
while (i <= lim) {
  if (i == 2) {
    lim <- lim   1
  } else {
    print(i)
  }
  i <- i   1
}
# [1] 1
# [1] 3
# [1] 4
# [1] 5
# [1] 6

(My only caution here is that if your increment of i is conditional on anything, there needs to be something else that prevents this from being an infinite loop. Perhaps this caution is unnecessary in your use-case, but it seems relevant to at least mention it.)

CodePudding user response:

The i is the for each value and that cannot be modified with i = i 1. We may use an if condition

for(i in 1:5){
if(i != 2)
  print(i)
}

-output

[1] 1
[1] 3
[1] 4
[1] 5

Also, if the intention is to subset a vector, why not use vectorized option

v1 <- 1:5
v1[v1 != 2]
  • Related