Customizing functions through parameters

Functions take parameters, that customize them for the given task. For example, the runif() function generates uniformly distributed values, which means that all outcomes have the same probability. By default, it takes the following parameters:

Input
runif(n, min = 0, max = 1)

The first parameter n is the number of values we want to generate. This is a mandatory parameter, that we need to define, in order for the function to work.

On the other hand, we can see that some of the parameters have default values defined by the equals sign =. This means that if we don’t explicitly specify these parameter in the brackets, the function will take the default ones. Let’s take a look at an example:

Input
runif(n = 5)
Output
[1] 0.6704463 0.3871817 0.1029936 0.9072686 0.6610819

The output is a numeric vector of 5 numbers. Each of them is between 0 and 1, since we did not change the default setting. If we changed the parameters min and max as well, we could further customize the output:

Input
runif(n = 5, min = 8, max = 9)
Output
[1] 8.594487 8.024123 8.109465 8.335108 8.299162

It is also possible to leave out the name of the parameters and simply type in the input values like this:

Input
runif(5, 8, 9)
Output
[1] 8.207784 8.143455 8.860226 8.651413 8.092435

However, in this case we must be cautious about the order of inputs, since each function has a default order for the parameters. If we don’t explicitly name the parameters we are setting, R will assume, that we set them in the predefined order.

Call existing R code through functions