2015-04-03 21 views
3

我需要計算函數的調用次數並在函數中使用它,但不是明確的。例如。例如:計算調用函數的數量(不明確)

f <- function(i,ncall) { 
print(paste("call to function number", ncall)) 
i = i^2 
return(i) 
} 

print(f(3,ncall=1)) 
print(f(4,ncall=2)) 

我想這樣做,但在ncall=Nf(a,N)時間不提供。對此沒有宇宙目的,只是想知道它是否可能。謝謝!

回答

3

這樣比較好嗎?

ncall <- 1 
f <- function(i) { 
    print(paste("call to function number", ncall)) 
    i <- i^2 
    ncall <<- ncall + 1 
    i 
} 

f(3) 
# [1] "call to function number 1" 
# [1] 9 
f(4) 
# [1] "call to function number 2" 
# [1] 16 
+0

哦!多麼簡單。謝謝! – 2015-04-03 17:13:49

9

您可以設置功能有自己的封閉環境:

f <- local({ 
    n <- 0 
    function(i, reset=FALSE) 
    { 
     n <<- if(reset) 0 else n + 1 
     print(paste("call to function number", n)) 
     i^2 
    } 
}) 

f(3) 
# [1] "call to function number 1" 
# [1] 9 
f(4) 
# [1] "call to function number 2" 
# [1] 16 
+0

最佳答案這個問題的方法。 – 2015-04-03 17:27:04