sai*_*eja 3 r matrix pass-by-value
我的问题与上面的问题完全相同,但我想要一个关于R的答案.我现在正在函数之间传递巨大的矩阵.矩阵中的数据在这些函数中没有改变.我只是使用矩阵.我的代码运行缓慢.我想知道是否存在使用全局变量或面向对象方式的替代方法.谢谢
R有参考传递(有点).将对象分配给另一个变量或传递给函数时,会创建另一个引用.但是,如果通过其中一个引用修改对象,那么就是在进行实际复制时.
f <- function(m) {
.Internal(inspect(m))
}
g <- function(m) {
m[1] <- 0
.Internal(inspect(m))
}
m <- matrix(1,1)
.Internal(inspect(m))
## @452e308 14 REALSXP g0c1 [NAM(2),ATT] (len=1, tl=0) 1
## ATTRIB:
## @42c8ee8 02 LISTSXP g0c0 []
## TAG: @2faaf98 01 SYMSXP g0c0 [MARK,LCK,gp=0x4000] "dim" (has value)
## @452e2d8 13 INTSXP g0c1 [NAM(2)] (len=2, tl=0) 1,1
# f shows that this is the same object (@452e308):
f(m)
## @452e308 14 REALSXP g0c1 [NAM(2),ATT] (len=1, tl=0) 1
## ATTRIB:
## @42c8ee8 02 LISTSXP g0c0 []
## TAG: @2faaf98 01 SYMSXP g0c0 [MARK,LCK,gp=0x4000] "dim" (has value)
## @452e2d8 13 INTSXP g0c1 [NAM(2)] (len=2, tl=0) 1,1
# g shows a newly allocated object (@3941998):
g(m)
## @3941998 14 REALSXP g0c1 [NAM(1),ATT] (len=1, tl=0) 0
## ATTRIB:
## @3b9fc80 02 LISTSXP g0c0 []
## TAG: @2faaf98 01 SYMSXP g1c0 [MARK,LCK,gp=0x4000] "dim" (has value)
## @3941ae8 13 INTSXP g0c1 [NAM(2)] (len=2, tl=0) 1,1
Run Code Online (Sandbox Code Playgroud)