仅在 R 函数范围内的全局变量
Global variable only within scope of R function
mat <- large matrix
f1 <- function(M) {
X <<- M
f1 <- function() {
do something with X but does not modify it
}
}
f1(mat)
X is no longer in scope
如何在 R 中实现上述伪代码中描述的内容?在 MATLAB 中,您可以使用 "global X"。 R中的等价物是什么?如果有 none,处理上述情况最有效的方法是什么:一个函数接受一个大矩阵作为参数,并且其中的许多不同的辅助函数作用于该矩阵(但不修改它)因此矩阵需要被复制尽可能少的次数。感谢您的帮助。
我不确定你想用你的辅助函数实现什么,但正如@Marius 在评论中提到的,内部函数应该已经可以访问 M
。因此像这样的代码可以工作:
f1 <- function(M) {
f2 <- function() {
f3 <- function() {
# f3 divides M by 2
M/2
}
# f2 prints results from f3 and also times M by 2
print(f3())
print(M * 2)
}
# f1 returns results from f2
return(f2())
}
mat <- matrix(1:4, 2)
f1(mat)
# [,1] [,2]
# [1,] 0.5 1.5
# [2,] 1.0 2.0
# [,1] [,2]
# [1,] 2 6
# [2,] 4 8
mat
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
这里没有必要在 f1
中执行 X <<- M
,特别是如果您不想在内存中复制 M
。
mat <- large matrix
f1 <- function(M) {
X <<- M
f1 <- function() {
do something with X but does not modify it
}
}
f1(mat)
X is no longer in scope
如何在 R 中实现上述伪代码中描述的内容?在 MATLAB 中,您可以使用 "global X"。 R中的等价物是什么?如果有 none,处理上述情况最有效的方法是什么:一个函数接受一个大矩阵作为参数,并且其中的许多不同的辅助函数作用于该矩阵(但不修改它)因此矩阵需要被复制尽可能少的次数。感谢您的帮助。
我不确定你想用你的辅助函数实现什么,但正如@Marius 在评论中提到的,内部函数应该已经可以访问 M
。因此像这样的代码可以工作:
f1 <- function(M) {
f2 <- function() {
f3 <- function() {
# f3 divides M by 2
M/2
}
# f2 prints results from f3 and also times M by 2
print(f3())
print(M * 2)
}
# f1 returns results from f2
return(f2())
}
mat <- matrix(1:4, 2)
f1(mat)
# [,1] [,2]
# [1,] 0.5 1.5
# [2,] 1.0 2.0
# [,1] [,2]
# [1,] 2 6
# [2,] 4 8
mat
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
这里没有必要在 f1
中执行 X <<- M
,特别是如果您不想在内存中复制 M
。