How to save an account in a recursive function in R?

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 this in R?

EDIT: code example:

test <- function(num)
{
  if(num>100)
    return(num)
  num <- num+4
  res <- test(num)
  return(res)
}
+4
source share
2 answers

Another approach that does not require 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)
}

Please note that the signature for the call is the testsame.

test(1)
##$res
##[1] 101
##
##$count
##[1] 25
+4
source

create a global variable using an operator <<-, and then index it in a recursive function.

counter <<- 0

then in your function to be used recursively simply:

counter <<- counter +1
+5
source

Source: https://habr.com/ru/post/1657102/


All Articles