Peutch
Peutch

Reputation: 773

R: How can a function assign a value to a variable that will persist outside the function?

This is probably easy but I am confused as hell with environments. I would like to use a call to a function to assign a value to a variable, but I need to be able to use that variable after the call. However, I assume, the variable created by the function only exist within the function environment. In short, I need something akin to a global variable (but I am a beginner with R).

The following code :

assignvalue = function(varname){
        assign(varname,1)
     }
assignvalue("test")
test

returns Error: object 'test' not found whereas I would like it to be equivalent to

test <- 1
test

I read something in the documentation of assign about environments, but I could not understand it.

Upvotes: 2

Views: 3551

Answers (1)

Thiago
Thiago

Reputation: 672

Say foo is a parameter of your function. Simply do this:

assignvalue <- function(foo) {
        varname <<- foo
}
assignvalue("whatever")
varname

The variable varname will point out to the value "whatever".

Upvotes: 1

Related Questions