Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep count in a recursive function in R?

Tags:

r

recursion

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)
}
like image 206
user4704857 Avatar asked Oct 07 '16 20:10

user4704857


People also ask

How do you count something in recursion?

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.

Is recursion always inefficient?

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.

Can you have 2 base cases for recursion?

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.


2 Answers

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
like image 183
JD Long Avatar answered Oct 20 '22 18:10

JD Long


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
like image 7
aichao Avatar answered Oct 20 '22 19:10

aichao