Search code examples
rmatrixscopeglobal-variablesmemory-efficient

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

How does one achieve what is described in the pseudocode above in R? In MATLAB, you can use "global X". What is the equivalent in R? If there is none, what is the most efficient way to deal with the scenario above: a function takes in a large matrix as an argument and many different helper function within it act on that matrix (but do not modify it) thus the matrix needs to be copied as few times as possible. Thanks for your help.


Solution

  • I am not sure what you'd like to achieve with your helper functions, but as @Marius mentioned in the comment, the inner functions should already have access to M. Hence codes like this would work:

    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
    

    There's no need to do X <<- M in f1 here, especially if you don't want a copy of M in memory.