[R] understanding recursive functions
Jeffrey Horner
jeff.horner at vanderbilt.edu
Thu Dec 18 23:33:28 CET 2008
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:
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()
Jeff
>
>
> Joe Boyer
> Statistical Sciences
> Renaissance Bldg 510, 3233-D
> Mail Stop RN0320
> 8-275-3661
> cell: (610) 209-8531
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
--
http://biostat.mc.vanderbilt.edu/JeffreyHorner
More information about the R-help
mailing list