Functions

# Up to now, we used functions that are pre-programmed in R or contained in a
# package we load.  The user can of course also define own functions. For
# example:

fMultiplyXY = function(x, y) {
    x * y
}

fMultiplyXY(3, 4)
## [1] 12
# When a function uses many arguments, it can be hard to remember the argument
# order.  In that case, it is useful to specify the argument names when calling
# the function, because then the order becomes irrelevant:

# Both give same result:
fMultiplyXY(x = 3, y = 4)
## [1] 12
fMultiplyXY(y = 4, x = 3)
## [1] 12
# One can also specify some arguments to be optional. For example:

# Here, the third argument ('z') is optional. By default, the function takes
# z=2.
fMultiplyXYZ = function(x, y, z = 2) {
    x * y * z
}

fMultiplyXYZ(2, 3)  # uses z=2
## [1] 12
fMultiplyXYZ(2, 3, 2)  # also uses z=2
## [1] 12
fMultiplyXYZ(2, 3, 4)  # uses z=4
## [1] 24