Re: R-beta: return()

Douglas Bates (bates@stat.wisc.edu)
25 Sep 1997 12:42:22 -0500


To: Bill Simpson <wsimpson@uwinnipeg.ca>
Subject: Re: R-beta: return()
From: Douglas Bates <bates@stat.wisc.edu>
Date: 25 Sep 1997 12:42:22 -0500
In-Reply-To: Bill Simpson's message of Thu, 25 Sep 1997 12:07:31 -0500 (CDT)

Bill Simpson <wsimpson@uwinnipeg.ca> writes:

> I have a question on the use of return(). (Nothing on it in the docs I
> have)

Because S and R are functional languages (i.e. based on functions), the
preferred way of communicating results is through the object that is
returned.  The problem in your example is that you do not assign the
result of the thingy(10) call in the definition of thingy2 so the
value is discarded.

Your code

> thingy<-function(k)
> {
> x<-5+k
> y<-5-k
> return(list(x=x,y=y))
> }
> 
> thingy2<-function()
> {
> thingy(10)
> cat("x,y:",x,y,"\n")
> }

works just fine if you either eliminate the "cat" call in thingy2
-----------------
thingy <-
  function(k)
{
  x <- 5+k
  y <- 5-k
  return(list(x=x,y=y))
}

thingy2 <-
  function()
{
  thingy(10)
}
----------------
R> thingy2()
$x
[1] 15

$y
[1] -5

or you assign the result of the call to thingy and use the components
of that object

R> thingy2
function () 
{
        t1 <- thingy(10)
        cat("x,y:", t1$x, t1$y, "\n")
}
R> thingy2()
x,y: 15 -5 

Generally the first method is preferred.  The idea of spending a lot
of time playing around with cat and dput to get pretty output is
deprecated.

Readers of the list are invited to make up their own "catcall" puns.
-- 
Douglas Bates                            bates@stat.wisc.edu
Statistics Department                    608/262-2598
University of Wisconsin - Madison        http://www.stat.wisc.edu/~bates/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request@stat.math.ethz.ch
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=