问题
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.
回答1:
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"
.
来源:https://stackoverflow.com/questions/25771304/r-how-can-a-function-assign-a-value-to-a-variable-that-will-persist-outside-the