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
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.
OK, so I'm not very bright. Here is the answer:
i <<- i + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With