[R] understanding recursive functions

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Fri Dec 19 01:59:48 CET 2008


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of 
> Ted.Harding at manchester.ac.uk
> Sent: Thursday, December 18, 2008 2:52 PM
> To: r-help at r-project.org
> Cc: joseph.g.boyer at gsk.com
> Subject: Re: [R] understanding recursive functions
> 
> On 18-Dec-08 22:33:28, Jeffrey Horner wrote:
> > joseph.g.boyer at gsk.com wrote on 12/18/2008 04:22 PM:
> >> I'm trying to understand the use of recursive functions described
> >> on page 45 of An Introduction to R by the R core development team.
> >> 
> >> A function is a list of expressions, which all get executed with
> >> only the last being assigned to a global variable, right? 
> >> So if a function refers recursively to itself, it should simply
> >> start with the first expression and go from there. At least that
> >> is my understanding of why the example given on page 45 works.
> >> 
> >> In light of the above, I would appreciate it if someone would
> >> understand why the following example does not work:
> >> 
> >> q <- function(x,h) {if (x < 2) {x <<- x+1; return(q(x))} else
> >> return(x)}
> >> 
> >> If x < 1, this should add 1 to x and go back to the beginning of
> >> the if expression, and the final result should be 2. So q(0) should
> >> return 2.
> >> But it returns an error message.
> > 
> > All references to x save one (the assignment with the <<- operator)
> > are found within the current frame, not by lexical scoping, and
> > hence is never changed... producing infinite recursion. The 
> following
> > at least fixes your example:
> > 
> > q <- function(x,h) {if (x < 2) {x <<- x+1; x <- x+1; 
> return(q(x))} else
> > return(x)}
> > ls() # no x in global env just yet
> > q(-10)
> > ls()
> 
> The following fixes it even more simply (using the same principles):
> 
>   q <- function(x,h){
>     if (x < 2) {u <- x+1; return(q(u))} else return(x)
>   }
> 
> Note that "<<-" is not necessary.
> 
> Just to test the method more thoroughly:
> 
>   q <- function(x,h){
>     if (x < 2) {u <- x+h; return(q(u,h))} else return(x)
>   }
> 
>   q(0,0.3)
> # [1] 2.1
> 
> Ted.
> 

I am by no means an expert in programming so I will defer to the experts. But assuming the OP was not intentionally trying to assign in a parent environment, couldn't the above function be written as

q <- function(x,h){if (x < 2) q(x+h,h) else return(x)

Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA  98504-5204
 
 



More information about the R-help mailing list