Recursive functions and global and local variables

I am writing a recursive function in R and I want it to change a global variable so that I know how many instances of the function were called. I do not understand why the following does not 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 result:

 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 result:

 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 
+4
source share
3 answers

You can use the local function to do the same, but without changing 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 that contains i . This method should be acceptable in packages submitted by CRAN, while changing the global environment is not.

+7
source

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

 i <<- i + 1 
+6
source

Give "i" as an argument to the function.

0
source

Source: https://habr.com/ru/post/1480095/


All Articles