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.
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"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.