3

I was reading the R Language Manual and wonder what value the Looping functions return. The Manuall say in section 3.3.2 Looping:

Each of the three statements [for, while, repeat] returns the value of the last statement that was evaluated. ... The value returned by a loop statement is always NULL and is returned invisibly.

So what value is returned, NULL or the value of the last statement evaluated in the Loop?

Regards, Oliver

Oliver
  • 312
  • 2
  • 9
  • read [this](http://stackoverflow.com/questions/11653127/what-does-the-function-invisible-do) first – mtoto Feb 26 '16 at 09:54
  • can whoever downvoted this question please explain why? – Jimi WIlls Feb 26 '16 at 10:35
  • [that](http://stackoverflow.com/questions/11653127/what-does-the-function-invisible-do) only explains why NULL is not printed when you execute a loop. – Jimi WIlls Feb 26 '16 at 10:35

1 Answers1

9

You're talking about this: https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Looping

x = for(i in 1:10){ i }
i
#[1] 10
x
#NULL
x <- while(i < 20){ i=i+1 }
i
#[1] 20
x
#NULL
x <- repeat { if(i>=30){break}; i=i+1 }
i
#[1] 30
x
#NULL

Very definitely NULL.

I checked and older versions of the documentation. The statement "The value returned by a loop statement statement is always @code{NULL} and is returned invisibly." first appears in R3.0.0 (it's not present in 2.9.0). It would appear there was a change of behaviour and documentation may not have been sufficiently cleaned up.

jicawi@JimisPC:~$ diff R-lang.2.9.0.texi R-lang.3.0.0.texi > R-lang.diff
jicawi@JimisPC:~$ grep -n NULL R-lang.diff 
82:> The value returned by a loop statement statement is always @code{NULL}
...

So, I installed R 2.9.0 and ran the same thing:

x = for(i in 1:10){ i }
x
#[1] 10
x <- while(i < 20){ i=i+1 }
x
#[1] 20
x <- repeat { if(i>=30){break}; i=i+1 }
x
#[1] 30

Very definitely the last statement :)

Bug report submitted: https://bugs.r-project.org/bugzilla/show_bug.cgi?id=16729

  • update: the bug was confirmed, fixed and report status now CLOSED:FIXED.

Well spotted!

Jimi WIlls
  • 348
  • 1
  • 10