Reputation: 1369
How can I store variables locally within a function.
testing <- function(number.info){
if (!exists('x')){
x <- 0
}
x <- x + number.info
return(x)
}
testing(2)
testing(2)
As we see here every time I run the function it returns the same value, as x is not being stored.
The motivation behind this is to create a function that can accrue information.
EDIT: Not a repeat question, i did check this answer before hand. The reason is that I don't need it useable outside the function. I just want the function to store it so as i input more data it outputs a 'smarter' result using this new information. I want to do with without using the global environment.
Upvotes: 2
Views: 729
Reputation: 79188
You can list the value to the global environment. Or the environment you are working from:
testing <- function(number.info){
if (!exists('x')){
x <- 0
}
x <- x + number.info
list2env(list(x=x),.GlobalEnv)
return(x)
}
testing(2)
[1] 2
testing(2)
[1] 4
If you do want to create a new environment then you can do something like:
myenv=new.env()
testing <- function(number.info){
if (!exists('x',envir = myenv)){
assign("x", 0,envir = myenv)
}
x=get("x",envir = myenv) + number.info
assign("x", x,envir = myenv)
return(x)
}
testing(2)
[1] 2
testing(2)
[1] 4
Upvotes: 3