1

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.

watchtower
  • 4,140
  • 14
  • 50
  • 92

1 Answers1

0

When the h() function is called you assign x to 3 which is local to that function. When it tries to evaluate x + y it doesn't find the definition of y in local function hence, it takes the value of y which is declared globally i.e 10. Hence, the output is 10 + 3 = 13. The value of y in g() function is local only to that function and not to h() function. The local environment of all the functions is different and independent of one another.

If you want y to maintain it's value from the g function you can pass the value of y in the h() function.

Update the two functions like this :

g <- function() {
     x <- 2
     y<-5 
     h(y)
}

h <- function(y) {
    x <- 3
    x + y
}

So now when you call the f() function you get output as expected

f()
#[1] 8

Also, if you update your y in your g() function to

g <- function() {
      x <- 2
      y <<-5 #Note the <<- operator. 
     h()  
}

What <<- does is it updates the value of y in the global environment. So the value of y which was 10 before in the global environment is now changed to 5. Hence, when you call f() now, you will get output as 8 and not 13.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213