Functions

Function is an object, as everything in R.

Hello world function

Function that sums two numbers.

sumNumbers <- function(x, y) {
  x + y
}

sumNumbers(1, 2)
# or better to name parameter when assigining values
sumNumbers(x=1, y=2)

Default parameter

The following function shows how to create parameter with a default value.

above <- function(x, n = 10) {
    use <- x > n
    x[use]
}

x <- 1:20
above(x, 10)

Calculating mean

Let's calculate mean of column in a matrix.

Lazy Evaluation

When function f does not use b parameter, it will never complain thanks to lazy evaluation.

Three dots ... argument

Can be used to pass multiple parameters and we do not want to list them all.

If we do not know number of arguments. The function prints all parameters we have passed into the function.

Find function's environment

Lexical Scoping

  • Typically, a function is defined in global environment.

  • You can have functions inside functions

R searches a variable in a series of environments to find appropiate value.

Lexical vs. Dynamic Scoping

What is returned when we execute f(3) function.

  • With lexical scoping, y is looked up by environment where g function has been created. In this case, in global environment.

  • With dynamic scoping, y is looked up by environment where the function was called. It is also referred as calling environment or parent frame.

The result is following.

Consequence of lexical scoping: all objects must be stored in memory and all function must have pointer to their environment.

More about scoping in R.

Scoping Rules - Example

For more information about scoping have a look here.

Last updated

Was this helpful?