It's not a good idea to modify the global environment directly from within a function. Usually it is a better idea just to return a value and let the user append it to where's necessary. (Just as Stibu explained).
However, what you can also do is to use nested environments like in the following modification of an example from the official R language definition:
fruitscollector <- function(){
fruitslist <- NULL
function(){
answer <- as.integer(readline(prompt="How Many?: "))
fruitslist <<- c(fruitslist, answer)
fruitslist
}
}
So when you first initialize a "fruitscollector" it returns just a function that can collect values.
foo <- fruitscollector()
Now every time you use foo
, a value will be added to the collection (and the whole collection is returned):
foo()
foo()
# etc
fruitslist
is stored in the parent environment of foo
, so not in the global environment where you can accidentally delete it.
edit
A more general idea would be to create an object (somewhat similar to what is called an "object" in OOP) with functions as methods, e.g.
collector <- function(){
stack <- NULL
list(
add = function(x) stack<<-c(stack, x),
get = function() stack,
empty = function() stack <<- NULL
)
}
Now the add
method will add to the stack, get
method will return the whole stack, and empty
method will empty it.
foo <- collector() # initialize
foo$get() # NULL
foo$add(1) # add 1 to the stack
foo$get() # 1
foo$add(3) # add 3 to the stack
foo$get() # 1 3
foo$add(1:5) # etc...