r - Recursive functions and global vs. local variables -


i'm writing recursive function in r, , want modify global variable such know how many instances of function have been called. don't understand why following doesn't work:

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

here 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 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 

you can use local function same thing without modifying global environment:

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

this neatly wraps testfun function in local environment holds i. method should acceptable in packages submitted cran, whereas modifying global environment not.


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -