Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

function

r

I have a function say,

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

So, for the first time function inc gets called, f will be 1, but the next time it gets called f value should be 2 and when the function inc gets called for the 3rd time f value should be 3 and so on...

How do I do it in R?

like image 400
user3664020 Avatar asked Jan 07 '23 12:01

user3664020


2 Answers

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

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

f <- getF() 

f is a function (the return value of getF) and it's enclosing environment is not the global environment, but the environment wherein f was defined. Look at environment(f). <<- assigns x into that environment: see ls(environment(f)) and get("x", environment(f)).

print(f(3))#4
print(f(4))#8
like image 72
jimifiki Avatar answered Jan 19 '23 01:01

jimifiki


This might be easier to understand, but creates an environment in the workspace as a side effect:

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
like image 36
Roland Avatar answered Jan 19 '23 00:01

Roland