r - Increase value of an object inside a function everytime it gets called -


i have function say,

inc <- function(t) {        f <- 1        t + f } 

so, first time function inc gets called, f 1, next time gets called f value should 2 , when function inc gets called 3rd time f value should 3 , on...

how do in r?

i use this. don't know if trick or hack:

getf <- function(){    x <- 1    function(t){       x <<- t + x    } }  f <- getf()  

f function (the return value of getf) , it's enclosing environment not global environment, environment wherein f defined. @ environment(f). <<- assigns x environment: see ls(environment(f)) , get("x", environment(f)).

print(f(3))#4 print(f(4))#8 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -