Function: Lexical Scoping
Can you identify the outcomes from the following examples?
Try to guess the outcomes without running the code.
Check the answer after running the code.
Did you get the logic of lexical scoping?
Example 1
rm(list = ls())
y <- 2
f <- function(x){
m <- x * y
return(m)
}
# First call
f(x=3)
# Second call
y <- 5
f(x=3)
Example 2
rm(list = ls())
y <- 2
f <- function(x){
y <- 4
fnew <- function(x){
z <- x*y
return(z)
}
m <- fnew(x)
return(m)
}
# First call
f(x=3)
# Second call
y <- 5
f(x=3)
Example 3
rm(list = ls())
y <- 2
fnew <- function(x){
z <- x*y
return(z)
}
f <- function(x){
y <- 4
m <- fnew(x)
return(m)
}
# First call
f(x=3)
# Second call
y <- 5
f(x=3)
Example 4
rm(list = ls())
a <- 1
b <- 2
f <- function(x){
z <- a*x + b
return(z)
}
g <- function(x){
a <- 2
b <- 1
m <- f(x)
return(m)
}
g(x=2)