1. Scope and precedence
You might be wondering why the course took a diversion into playing with environments.
2. Accessing variables outside functions
The answer is that when you call a function, R gives it an environment to store its variables. With this example, x will be added to the environment, then the x times y calculation will be performed in that environment.
You may have noticed a problem: there is no y argument to the function.
So when you call the function, you get an error stating that y wasn't found.
Let's make one small change to the code: we define y outside the function. Now the function call works. R used the same process here as you saw earlier with the exists function. When it couldn't find y inside the function's environment, it looked in the parent environment.
3. Accessing function variables from outside
Now you've run your multiplication code, what happens if you try to print x?
x is being looked for in the global environment, but it isn't there. The function's environment isn't a parent of the global environment -- it's a child instead.
So R can't look there, which means that x can't be found, and you get an error.
So a function can look for variables outside its environment, but the reverse isn't true: you can't look inside the function's environment from outside.
4. What's best? Inside or outside?
In this variation, y is defined inside the function and in the global environment.
If you call x_times_y, which version gets used? Remember that R will search for variables inside the function first. If it finds y there, it doesn't need to look in the parent environment.
So the answer is ten times six.
5. Passed in vs. defined in
One extra line has been added to the code. Now x is passed into the function and also defined inside the function body. So which gets used?
When the function is first called, x is set to ten in the function's environment. Then, as R works through the function body, x is changed to nine.
So values defined inside the function take precedence over values passed into the function, and the answer is nine times six.
6. Let's practice!
Let's do this.