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:

> computeSquare <- function(x) {
+   sq <- x^2
+   return(sq)
+ } 

The variable sq is local to our function computeSquare() and can not be accessed from outside:

> computeSquare(3)
[1] 9
> print(sq)
Error in eval(expr, envir, enclos): object 'sq' not found

On the other hand, we can use variables inside a function that are not necessarily defined within the function. For example, take this function:

> computeSum <- function(x) {
+   return(x + y)
+ } 

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.

> y <- 100
> computeSum(10)
[1] 110

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.

  1. Consider the following code:

    > x <- 20
    > computeSum <- function(x, y = 10) {
    +   z <- x + y
    +   return(z)
    + }

    Given the above code was run, which value does computeSum(x = 4, 6) produce?