Variations on R Functions

This post demonstrates how to work with variations on R functions using a few examples with `rnorm`, `seq`, and `rep`. There’s the default signature, order, and behavior for parameters wit these functions. Also, there are ways to change the default behavior prescribed by the signature.

You can view these variations by looking at the function prototypes and signatures in the help documentation. The docs explain which parameters are required and which parameters are optional. You can also read more about the calculations that go on behind the scenes for specific parameters, and much more.

Invoking Help and an Example of a Function Variation

To get access to the help documentation for a function, preface it with the ‘?’ character. For example, if I type `?rnorm`

Using `rnorm()` as the example, we read that `n` is required while the other parameters have default values and are consequently optional. From the documents, we also learn the official parameter names, and that the runtime supports named parameters. So I can then, for example, call `rnorm()` with the parameters is any order. Given:

v_standard <- rnorm(3, 5, 2)
v_alt <- rnorm(mean=5, sd=2, n=3)
print(v_standard)
print(v_alt)

…both v_standard and v_alt produce a vector which contains 3 numbers normalized along the mean of 5 with a standard deviation of 2 about that mean.

More Examples and Explanations

Here are some additional variations on R functions that I’ve worked with thus far.

Check out `seq()`

We see there is a variation from the default where `by` is calculated when it is left out and `length.out` is specified. Given:

seq(from = 1, to = 10, length.out = 5)

…we learn from the documents that the step (i.e. “by) will be calculated as:

`((10 - 1) / (5 - 1)) => 9/4 => 2.25`

And, sure enough, R Studio output is:

> seq(from = 1, to = 10, length.out = 5)
[1] 1.00 3.25 5.50 7.75 10.00

`rep()` has some interesting variations too:

The `each` parameters is interesting. It allows one to define how many times each element of the input vector x will be repeated:

…and so on.

The takeaways from these notes are:

• Specify the `?` character in front of a function to get the help docs
• The help docs will explain all of the variations available for a function
• Functions support named parameters

Categories: R Programming