Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What value do the loop functions return in R

Tags:

r

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

like image 584
Oliver Avatar asked Dec 16 '25 14:12

Oliver


1 Answers

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!

like image 105
Jimi WIlls Avatar answered Dec 19 '25 05:12

Jimi WIlls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!