Functions
Function is an object, as everything in R.
Hello world function
Function that sums two numbers.
Default parameter
The following function shows how to create parameter with a default value.
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
...
argumentCan 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 whereg
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