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
source share