Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive functions and global vs. local variables

I'm writing a recursive function in R, and I want it to modify a global variable such that I know how many instances of the function have been called. I don't understand why the following doesn't work:

i <- 1

testfun <- function( depth= 0 ) {

  i <- i + 1
  cat( sprintf( "i= %d, depth= %d\n", i, depth ) )
  if( depth < 10 ) testfun( depth + 1 )
}

Here is the output:

i= 2, depth= 0
i= 2, depth= 1
i= 2, depth= 2
i= 2, depth= 3
i= 2, depth= 4
i= 2, depth= 5
i= 2, depth= 6
i= 2, depth= 7
i= 2, depth= 8
i= 2, depth= 9
i= 2, depth= 10

Here is the expected output:

i=2, depth= 0
i=3, depth= 1
i=4, depth= 2
i=5, depth= 3
i=6, depth= 4
i=7, depth= 5
i=8, depth= 6
i=9, depth= 7
i=10, depth= 8
i=11, depth= 9
i=12, depth= 10
like image 531
January Avatar asked Dec 09 '22 15:12

January


2 Answers

You can use the local function to do the same thing but without modifying the global environment:

testfun <- local({
  i <- 1
  function( depth= 0 ) {
    i <<- i + 1
    cat( sprintf( "i= %d, depth= %d\n", i, depth ) )
    if( depth < 10 ) testfun( depth + 1 )
  }
})

This very neatly wraps the testfun function in a local environment which holds i. This method should be acceptable in packages submitted CRAN, whereas modifying the global environment is not.

like image 157
Steve Weston Avatar answered Dec 11 '22 07:12

Steve Weston


OK, so I'm not very bright. Here is the answer:

i <<- i + 1
like image 38
January Avatar answered Dec 11 '22 07:12

January