On 18-Dec-08 22:33:28, Jeffrey Horner wrote: > joseph.g.bo...@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. -------------------------------------------------------------------- E-Mail: (Ted Harding) <ted.hard...@manchester.ac.uk> Fax-to-email: +44 (0)870 094 0861 Date: 18-Dec-08 Time: 22:51:41 ------------------------------ XFMail ------------------------------ ______________________________________________ R-help@r-project.org 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.