I am reading Hadley Wickham's Advanced R to understand this language in a better way. I came across a section in the chapter Environments where he talks about the preference given to local variable over global variable.
For instance,
h <- function(){
x<-10
function(){
x
}
}
i<-h()
x<-20
i()
This could would return 10
and not 20
because local x
overrides global x
.
However, when I applied similar logic to the below code, global variable y
overrode local y
.
x <- 0
y <- 10
f <- function() {
x <- 1
g()
}
g <- function() {
x <- 2
y<-5 #Added by me
h()
}
h <- function() {
x <- 3
x + y
}
f()
The output is 13
. I would have expected 8
because I have created a local variable y
in h()
's calling function g()
. Isn't it?
I'd appreciate any comments and guidance.