Increase the value of an object inside a function every time it is called

I have a say function,

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

So, the first time the function is called inc, it fwill 1, but the next time it gets the name f, the value should be 2and when the function incgets the call for the third value it fshould be 3and so on ...

How do I do this in R?

+4
source share
2 answers

I usually use this. I don't know if this is a trick or hack:

getF <- function(){
   x <- 1
   function(t){
      x <<- t + x
   }
}

f <- getF() 

f - ( getF), , , f . environment(f). <<- x : . ls(environment(f)) get("x", environment(f)).

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

, :

inc <- function(t) {
  if (!exists("e")) {
    e <<- new.env()
    e$x <- 1
  }

  e$x <- e$x + t
  e$x
}

inc(2)
#[1] 3
inc(2)
#[1] 5
+3

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


All Articles