Reputation: 773
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
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