Using global variable in function

删除回忆录丶 提交于 2019-12-13 07:24:42

问题


I have a very big dataset and I analyze it with R.

The problem is that I want to add some columns with different treatments on my dataset AND I need some recursive function which use some global variable. Each function modify some global variable et create some variables. So the duplication of my dataset in memory is a big problem...

I read some documentation: if I didn't misunderstand, neither the use of <<- nor assign() could help me...

What I want:

mydata <- list(read.table(), ...)
myfunction <- function(var1, var2) {
   #modification of global mydata
   mydata = ...
   #definition of another variable with the new mydata
   var3 <- ...
   #recursive function
   mydata = myfunction(var2, var3)
}

Do you have some suggestions for my problem?


回答1:


Both <<- and assign will work:

myfunction <- function(var1, var2) {
   # Modification of global mydata
   mydata <<- ...
   # Alternatively:
   #assign('mydata', ..., globalenv())

   # Assign locally as well
   mydata <- mydata

   # Definition of another variable with the new mydata
   var3 <- ...

   # Recursive function
   mydata = myfunction(var2, var3)
}

That said, it’s almost always a bad idea to want to modify global data from a function, and there’s almost certainly a more elegant solution to this.

Furthermore, note that <<- is actually not the same as assigning to a variable in globalenv(), rather, it assigns to a variable in the parent scope, whatever that may be. For functions defined in the global environment, it’s the global environment. For functions defined elsewhere, it’s not the global environment.



来源:https://stackoverflow.com/questions/32759658/using-global-variable-in-function

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