在函数中使用全局变量 [英] Using global variable in function
问题描述
我有一个非常大的数据集,并使用R对其进行了分析.
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...
我阅读了一些文档:如果我没有误会,使用<<-
和assign()
都不会帮助我...
I read some documentation: if I didn't misunderstand, neither the use of <<-
nor assign()
could help me...
我想要什么:
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?
推荐答案
<<-
和assign
均可使用:
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.
此外,请注意,<<-
实际上与在globalenv()
中分配给变量不同,而是在父范围中分配给变量,无论可能是什么.对于在全局环境中定义的功能,它是全局环境.对于在其他地方定义的功能,它不是全局环境.
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.
这篇关于在函数中使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!