R - Binding values to a symbol


  • Scoping: Binding values to a symbol
    • If we define a function named "mean", how R will recognize it? 
    •  > mean <- function(x,y){  
       +   x+y  
       + }  
       > mean(1,4)  # it will search mean from user environment (or global environment) first
       [1] 5  
       > search()  # check search order in R
        [1] ".GlobalEnv"    "tools:rstudio"   "package:stats"   "package:graphics" "package:grDevices"  
        [6] "package:utils"   "package:datasets" "package:methods"  "Autoloads"     "package:base"    
      
    • Free variable, the variable is searched from environment in which the function is defined(Lexical Scoping).
    • If can't find in the environment, search top-level environment (workspace, packages)
    •  > z <- 11  
       > fun <- function(x,y){  
       +   x+y-z  # z is a free variable here
       + }  
       > fun(12,13)  
       [1] 14  
      
    • Define function inside a function
    •  > make.power <- function(n){  
       +   pow <- function(x){  
       +     x^n  
       +   }  
       +   pow  
       + }  
       > cube <- make.power(3)  
       > cube(2)  
       [1] 8  
       > ls(environment(cube))  # list what in function closure (environment)
       [1] "n"  "pow"  
       > get("n",environment(cube))  # get value of n
       [1] 3  
       > get("pow",environment(cube))  # get value of pow
       function(x){  
           x^n  
         }  
       <environment: 0x000000000856e658>  
      
    • Lexical Scoping and Dynamic Scoping(searched from environment in which the function is called)
    •  > a <- 1  
       > f <- function(b){  
       +   a <- 10  
       +   a + b + g(b)  # a is 10 in f() and 1 in g(b) since R is using lexical scoping, a is 10 in g(b) if it is Dynamic Scoping 
       + }  
       > g <- function(b){  
       +   a + b  
       + }  
       > f(1)  
       [1] 13  
      

No comments:

Post a Comment