递归函数和全局与局部变量

Jan*_*ary 4 recursion r global-variables local-variables

我正在R中编写一个递归函数,我希望它能修改一个全局变量,以便知道调用了多少个函数实例.我不明白为什么以下不起作用:

i <- 1

testfun <- function( depth= 0 ) {

  i <- i + 1
  cat( sprintf( "i= %d, depth= %d\n", i, depth ) )
  if( depth < 10 ) testfun( depth + 1 )
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

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
Run Code Online (Sandbox Code Playgroud)

这是预期的输出:

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
Run Code Online (Sandbox Code Playgroud)

Ste*_*ton 8

您可以使用该local函数执行相同的操作但不修改全局环境:

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 )
  }
})
Run Code Online (Sandbox Code Playgroud)

这非常巧妙地将testfun功能包含在一个本地环境中i.在提交CRAN的包中,此方法应该是可接受的,而修改全局环境则不然.


Jan*_*ary 6

好的,所以我不是很聪明.这是答案:

i <<- i + 1
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您的函数的父级应该是全局环境,以便按预期工作.如果你的函数是在另一个函数中定义的并且在那里定义了i,那么增量将发生在函数的父环境i中.我希望我能混淆你.. :) (3认同)