Limiting variable scope

后端 未结 4 2119
北荒
北荒 2020-11-30 12:50

I\'m trying to write a function, which limits the scope of R variables. For example,

source(\"LimitScope.R\")
y = 0
f = function(){
   #Raises an error as y          


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 13:17

    You can force a variable to be the local version with this function:

    get_local <- function(variable)
    {
      get(variable, envir = parent.frame(), inherits = FALSE)  
    }
    

    Compare these cases

    y <- 0    
    f <- function()
    {
      x <- y
    }    
    print(f())        # 0
    
    y <- 0    
    f <- function()
    {
      y <- get_local("y")
      x <- y
    }    
    print(f())        # Error: 'y' not found
    

    Depending on what you are doing, you may also want to check to see if y was an argument to f, using formalArgs or formals.

    g  <- function(x, y = TRUE, z = c("foo", "bar"), ...) 0
    
    formalArgs(g)
    # [1] "x"   "y"   "z"   "..."
    
    formals(g)
    #$x
    #
    #
    #$y
    #[1] TRUE
    #
    #$z
    #c("foo", "bar")
    #
    #$...
    

    EDIT: The more general point of 'how to turn off lexical scoping without changing the contents of functions' is harder to solve. I'm fairly certain that the scoping rules are pretty ingrained into R. An alternative might be to use S-Plus, since it has different scoping rules.

提交回复
热议问题