I have a recursive function in R. I would like to track it and know how many times the function is called during the procedure. How can I do it in R?
EDIT: sample code:
test <- function(num)
{
if(num>100)
return(num)
num <- num+4
res <- test(num)
return(res)
}
Algorithm: If size of string str2 is greater then string str1 or size of string str1 is 0 then, return 0. Otherwise, Check if string str2 is present in str1 as substring or not. if present then, increment the count of occurrence and recursively call for other substring.
Recursive algorithms are often inefficient for small data, due to the overhead of repeated function calls and returns. For this reason efficient implementations of recursive algorithms often start with the recursive algorithm, but then switch to a different algorithm when the input becomes small.
A recursive implementation may have more than one base case, or more than one recursive step. For example, the Fibonacci function has two base cases, n=0 and n=1.
create a global variable using the <<-
operator then index it in the recursive function.
counter <<- 0
then in your function that will be used recursively simply:
counter <<- counter +1
Another approach that does not require a global and <<-
is:
test <- function(num, count=0) {
if(num > 100)
return(list(res=num, count=count))
num <- num+4
res <- test(num, count+1)
return(res)
}
Note that the signature for invoking test
is the same.
test(1)
##$res
##[1] 101
##
##$count
##[1] 25
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