13.4 Environment
When you start writing more complicated code, you might get confused at some point about the scope of variables. First, you should know that variables that are defined within a function are only available within this function, but not from outside. For example, consider this function:
The variable sq
is local to our function computeSquare()
and can not be accessed from outside:
On the other hand, we can use variables inside a function that are not necessarily defined within the function. For example, take this function:
In many programming languages, this would be an error, because y
is not defined inside the function. In R (and python, too), this is valid code. R will first search for the value of y
inside the function (the smallest scope). If it can’t find it there, R will look for y
in the environment.
This behaviour is sometimes a bit confusing, so it’s good to be aware of it.
13.4.1 Exercises: Environment
See Section 18.0.35 for solutions.
Consider the following code:
Given the above code was run, which value does
computeSum(x = 4, 6)
produce?