简体   繁体   English

如何在R中继续计算递归函数?

[英]How to keep count 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. 我在R中有一个递归函数。我想跟踪它并知道在该过程中调用该函数的次数。 How can I do it in R? 我怎么能在R?

EDIT: sample code: 编辑:示例代码:

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

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的签名是相同的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM