weird [lack of] control…

When I ran

[sourcecode language=”r” gutter=”false”]
> test=NULL
> for (i in 1:10){
+ if (i%%2!=0){
+ test=c(test,i)
+ i=i+2}}
> test
[1] 1 3 5 7 9
[/sourcecode]

I was expecting the same output as

[sourcecode language=”r” gutter=”false”]
> test=NULL
> i=1
> while (i<11){
+ if (i%%2!=0){
+ test=c(test,i)
+ i=i+2}
+ i=i+1}
> test
[1] 1 5 9
[/sourcecode]

So this means that the dummy index in R “for” loops cannot be tweaked that easily. I seem to remember doing this kind of (dirty) tricks with earlier versions… Now, Alessandra and Robin think this is a good thing that the for loop is robust against this kind of non-sense, so I may be a minority in complaining about this lack of control [for me, if not for for].

5 Responses to “weird [lack of] control…”

  1. Martin Maechler's avatar
    Martin Maechler Says:

    “Of course”, I’m with Alessandra, Robin, Martyn, …
    If you want tricks manipulating i, you’d use a version of while(), i.e., while() or repeat.

    The idea is that the *reader* of for(….) should rely on what (s)he sees, whereas with while() or repeat “you” know that the looping may be complicated.
    .. and of course, the above is not quite true, insofar as ‘break’ still works {and rightly so!} inside a for(..) {..clause..}.

  2. The reason for this behaviour is that for loops in R are very general. Although it is common to step through an integer sequence, the general syntax is “for (i in seq)” where seq can be any vector, even a list. For example e.g. “for (i in LETTERS) print(i)” prints out the letters of the alphabet.

    Whatever you do to “i” inside the loop, it will be set to the next element of seq (as evaluated before R enters the loop) on the next iteration.

  3. I don’t understand the second code piece…

    • Thanks, John! There is a problem with (my?) WordPress editor in that it erases some lines written in sourcecode mode from one editing to the next. I have rewritten the complete code once again but it may vanish again…

Leave a Reply

Discover more from Xi'an's Og

Subscribe now to keep reading and get access to the full archive.

Continue reading