[R] Help me get this function to work...

Duncan Murdoch murdoch at stats.uwo.ca
Mon Jul 13 21:56:33 CEST 2009


On 7/13/2009 3:21 PM, Mark Knecht wrote:
> On Mon, Jul 13, 2009 at 12:08 PM, David Winsemius<dwinsemius at comcast.net> wrote:
>> In R a function only returns the last evaluation, so you need to wrap up all
>> of the local results into a list at the end of the function.
>>
>>
> 
> <SNIP>
>>
>> David Winsemius, MD
>> Heritage Laboratories
>> West Hartford, CT
>>
> 
> How important it is to wrap the list in a return statement, ala
> 
> return(list(ShrubCover.df, TreeCover.df, TotalCover.df))
> 
> or
> 
> answer <- list(ShrubCover.df, TreeCover.df, TotalCover.df)
> return(answer)

Those are almost identical.

The only difference is that the second version will leave the local 
variable "answer" in the evaluation frame.  For most functions the 
evaluation frame disappears after the return, but sometimes it lives a 
while longer.

For example, you can return it explicitly by putting "environment()" as 
one of the return values.  More commonly it is returned implicitly as 
the environment of a function created during evaluation, e.g.

 > buildf <- function() {
+   f <- function(x) x + 1
+   return(f)
+ }
 > g <- buildf()
 > g(5)
[1] 6
 > ls(environment(g))
[1] "f"

The last command looks in the environment of g, and sees the local 
variable f there, of which g is a copy.  If you had done

answer <- f
return(answer)

you'd also see answer there.

Duncan Murdoch




More information about the R-help mailing list