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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With