[R] return() in nested functions

Duncan Murdoch murdoch at stats.uwo.ca
Sat Jul 14 13:31:47 CEST 2007

On 14/07/2007 7:16 AM, Mark Hempelmann wrote:
> Dear WizaRds,
> 	After consulting different sources I am still unable to understand the 
> correct use of return() in nested functions. To illustrate the problem:

return() knows nothing about nested functions.  It just returns from the 
current function.

In most respects, nested functions are just like any other functions in 
R.  The only important difference is the attached environment, which 
affects what is visible from within the function, and where <<- stores 

> f <- function(x,y,type){
> 	est1<-function(x,y){
> 	z=x+y
> 	out(x,y,z)}
> 	est2<-function(x,y){
> 	z=x*y
> 	out(x,y,z)}
> 	out<-function(x,y,z)
> 	return(x,y,z)

Don't ignore the warning you saw from this!  Deprecated things 
eventually become defunct. You want return(list(x, y, z))

> if (type=="est1") est1(x,y)
> if (type=="est2") est2(x,y)
> }
> test<-f(1,2,type="est1") # gives Null for test

The result of the first if is the value from the call to est1.  The 
result of the second if is NULL.  That's what your function returned.

If you had wrapped those calls in return() you'd get what I think you 

if (type=="est1") return(est1(x,y))
if (type=="est2") return(est2(x,y))

because the return() causes the function to exit and return a value.

Duncan Murdoch

> However, without the second 'if' condition, it works properly:
> Warning message:
> multi-argument returns are deprecated in: return(x, y, z)
>> test
> $x
> [1] 1
> $y
> [1] 2
> $z
> [1] 3
> Basically, the function I am working on is of the above structure, be it
> more complex. I would like f to return the results of function 'out' to 
> the user in the assigned variable, e.g. 'test'. i did consult try() and 
> tryCatch(), but it doesn't seem to be what I am looking for.
> Thank you for your help and understanding
> mark
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list