在函数中修改变量的内存有效方法
Memory efficient way to modify a variable within a function
问题
我想写一个函数来修改一个大矩阵的每一列,x:
f = function(x){
# do something to x
# return x
}
因为x很大,我想修改"in place",即不创建副本。但是,我的理解是,在R中,函数是"copy on modify." 也就是说,如果我在函数f中修改x,R将复制 x.
建议的解决方案(更新:不起作用!有关详细信息,请参阅下面的答案。)
所以看来最好的办法就是修改全局变量,即
f = function(x){
x = deparse(substitute(x))
x = get(x, envir = globalenv())
# do something to x
}
问题
但是,SO 上的人对将全局变量传递给 R 中的函数非常消极。有些人甚至因为询问它而被否决。
我的问题是:在 R 中执行此类操作的最佳方法是什么?
这里已经讨论过这个问题:
Pass an object to a function without copying it on change
你的第二种方法并没有真正解决问题。这是我 运行 的测试,结果是 mem_used()
library(pryr)
mem_used()
#41.3 MB
x <- matrix(1:1000000000, ncol=1000)
mem_used()
#4.04GB
f2<- function(x){
print(mem_used())
x = deparse(substitute(x))
print(mem_used())
x = get(x, envir = globalenv())
x<- x+1
print(mem_used())
x
}
x <- f2(x)
#4.04 GB
#4.04 GB
#12 GB
mem_used()
#8.04GB
问题
我想写一个函数来修改一个大矩阵的每一列,x:
f = function(x){
# do something to x
# return x
}
因为x很大,我想修改"in place",即不创建副本。但是,我的理解是,在R中,函数是"copy on modify." 也就是说,如果我在函数f中修改x,R将复制 x.
建议的解决方案(更新:不起作用!有关详细信息,请参阅下面的答案。)
所以看来最好的办法就是修改全局变量,即
f = function(x){
x = deparse(substitute(x))
x = get(x, envir = globalenv())
# do something to x
}
问题
但是,SO 上的人对将全局变量传递给 R 中的函数非常消极。有些人甚至因为询问它而被否决。
我的问题是:在 R 中执行此类操作的最佳方法是什么?
这里已经讨论过这个问题:
Pass an object to a function without copying it on change
你的第二种方法并没有真正解决问题。这是我 运行 的测试,结果是 mem_used()
library(pryr)
mem_used()
#41.3 MB
x <- matrix(1:1000000000, ncol=1000)
mem_used()
#4.04GB
f2<- function(x){
print(mem_used())
x = deparse(substitute(x))
print(mem_used())
x = get(x, envir = globalenv())
x<- x+1
print(mem_used())
x
}
x <- f2(x)
#4.04 GB
#4.04 GB
#12 GB
mem_used()
#8.04GB