How is value assigned to a variable in R

r

#1

I have created a function and in that I have created a variable z.

Next, I have assigned a value of z inside the function and a value outside the function. I was hoping that the value of z which is outside the function will influence the value of variable z but I am getting opposite result

f <- function(x) {
        g <- function(y) {
                y + z
        }
        z <- 4
        x + g(x)
}

z<-10
f(3)

and I am getting 10 when I ran in R but I was thinking that answer would be 16


#2

@harry

Answer 10 seems like the right answer. Let us execute things as would be run by your computer:

z gets assigned a value of 10, but immediately after that f is called with parameter x = 3

In function f, you define new function g and re-assign the value of z to be 4. Next you call

x + g(x)

which is equal to

3 + g(3)

which is

3 + 3 + 4

which is 10