Saturday, 10 December 2016


Which environment you are using in R matters, but we generally ignore this fact. Here is a pretty simple example of when the environment does matter in a context where such problems often arise—where we define an object that will be called by a function.

The two-function problem

The main function (ending in “a”) takes three arguments: x, y, z and feeds them to a second function (ending in “b”). This “b” function only accepts x as an argument, but the function uses y and z, in addition to x (not ideal function writing).

Option 1: Non-nested functions

The first pair of functions (1a and 1b) are not nested, meaning test1b is not defined within test1a.

## Error in print(rep(x, y * z)): object 'y' not found

And we get an error: R cannot find y (or z). This error occurs because the function test1b lives on a different level (environment) than the environment in which we defined x, y, z. The three variables are defined within the context of the function test1a, but test1b is defined outside of test1a and only has access to the variable x, which we pass it through its x argument.

One solution: nest the functions…

Option 3: Write clearer functions

There other ways to fix the error in Option 1. The one you would probably hear from StackOverflow is to write better functions (i.e. name all the arguments the function needs). Errors within user-defined functions often come from users (me) getting lazy and calling objects within the function that have not been passed to the function. This tendency is a bit sloppy and, as Option 1 demonstrates, error prone.

The fix: pass all three arguments from the first (a) function to the second (b) function.

## [1] 1 1 1 1 1 1

Success. Plus, you won’t get reprimanded for sloppy scripting.

Wrap up

Environments matter. Sloppy coding can remind you how they matter. Loops also will remind you how they matter (for instance, lapply vs. for loops while updating data.tables).