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

那年仲夏 提交于 2019-12-24 00:53:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!