[Rd] Enlightenment sought and a possible buglet in vector.Rd

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Dec 2 11:46:38 CET 2005


On Fri, 2 Dec 2005, Berwin A Turlach wrote:

[...]

> The second behaviour that I cannot explain was produced by code
> written by somebody else, namely:
>
>      > foo
>      function(x){
>          z <- x/4
>          while( abs(z*z*z-x) > 1e-10 ){
>             z <- (2*z+x/z^2)/3
>          }
>      }
>
> The documentation of function() says that if "the end of a function is
> reached without calling 'return', the value of the last evaluated
> expression is returned."  And this seems to happen in this case:

Yes, but that value can be returned with R_Visible set to 0, by calling 
invisible() _or otherwise_.

>      > z <- foo(3)
>      > z
>      [1] 1.442250
>
> However, my understanding was always that the return value of a
> function issued on the command line will be printed; except, of
> course, if invisible() is used to return the value.  This is not the
> case for the above function:
>
>      > foo(3)
>
> produces no output.  And this had us stunned for some time.  On the
> other hand:
>
>      > ( foo(3) )
>      [1] 1.442250
>
> So my question is why does R, when "foo(3)" is issued on the command
> line, not print the value returned by the function?

R does not print the value of a while() loop.  Try

x <-3
z <- x/4
while( abs(z*z*z-x) > 1e-10 ){
   z <- (2*z+x/z^2)/3
}
.Last.value

and you are seeing no different.  (Look up the code of do_while for why.)

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list