A few extras from our first lab.

Functions and variables scope

Let’s look at the following code. We start by defining a function “addOne” which simply adds 1 to the variable past to it:

addOne <- function(i){
  i = i + 1
  i
}

addOne(2)
## [1] 3

Now, look at the following code and think of what the value of i should be after calling the function:

i = 1
addOne(i)
print(i)

The value of i after calling the function addOne is still 1

This is because R passes the arguments by value. This means that the variable i inside your function addOne is not the same i as outside the function. You can think of it as a temporary copy of the initial i value, this copy disapearing into thin air after the function ends.

So, what if you need a function that modifies a variable from your main program? The solution is to use the returned value of the function. In this simple example, you would write something like this:

i = 1
i = addOne(i)
print(i)
## [1] 2

Note that the name of the variable in the main program and in the function do not have to be the same:

j = 1
addOne(j)
## [1] 2
print(j)
## [1] 1
j = addOne(j)
print(j)
## [1] 2