[R] About the recursion in R

Duncan Murdoch murdoch.duncan at gmail.com
Tue Oct 26 23:37:58 CEST 2010


On 26/10/2010 5:17 PM, Xiuquan Wang wrote:
> Hi,
>
> I am now using R to implement a stepwise algrithom which includes a
> recursion function.
> e.g:
> --------------------------------
> a = 1
> *f_recursion* = function(id)
> {
>        b = a + id;   #: row A
>        if (...){ a = a +1;* f_recursion*(b) }  #: row B

The statement a = a + 1 creates a new local variable named a, it doesn't 
modify the existing global one.  To do that you need to use

a <<- a + 1

Duncan Murdoch

>        else{ .... }
> }
> ----------------------------------
> I find that if the code '*f_recursion*(b)' in row B is invoked, that means
>   'a' equals to 2 now. But in the procedure of '*f_recursion*(b)', the 'a'
> still equals the initial value 1.
>
> I don't know why, maybe it is a bug for R. Dose R support recursion
> function?
>
>
> Look forward to your reply, thanks a lot!
>



More information about the R-help mailing list