weird [lack of] control…

When I ran

> 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

I was expecting the same output as

> 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

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 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 to xi'an Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.