Variations on R Functions

Like many programming languages, there are variations on R functions. There’s the default signature, order, and behavior for parameters. 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

Help docs for the rnorm function.

Using rnorm() as the example, we infer that n is required while the other parameters have default values and are consequently options. From the documents, we also learn the official parameter names, and this implies (accurately) that the syntax 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)

…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

The previous example is a bit boring. Here are some more interesting variations on R functions that I’ve worked with thus far.

Check out seq()

R Programming seq function docs.

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:

R Programming rep() function docs.

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

Rep function using each.

…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

Tags: ,

Leave a Reply

%d bloggers like this: