1. Passing arguments between functions
In this lesson, you'll learn how to pass arguments from one function to another.
2. Calculating the geometric mean
Let's consider the example of calculating the geometric mean of some numeric vector, x.
The algorithm is straightforward. You take the logarithm of x, then calculate its arithmetic mean, then exponentiate the result.
3. Wrapping this in a function
Turning this into a function is simple. The function takes an x argument, and the script can simply be placed into the body with no messing about.
4. Handling missing values
There is one little complication: you need a way to deal with missing values.
The standard way of doing this is to give calc_geometric_mean an na-dot-rm argument, and set the default to FALSE. Na-dot-rm is the conventional name for an argument that removes missing values before any calculations occur. It can be found in many summary statistic functions like median or max, or -- as you see here -- mean.
As well as changing the signature, you must also change the body of the function. Pass calc_geometric_mean's na-dot-rm argument to mean's na-dot-rm argument using na-dot-rm equals na-dot-rm.
5. Using ...
The ellipsis, or dot-dot-dot, argument allows you to simplify your code a little bit.
Instead of explicitly naming na-dot-rm and setting a default and passing it to mean, you just say "accept any other arguments into calc_geometric_mean, then pass them to mean".
6. The tradeoff
Using dot-dot-dot here has two advantages, one obvious and one less so. The obvious advantage is that it's less typing for you. The subtler one, that's more important is that if the signature of the inner function changes, your code doesn't need to change to match it.
For example, if the mean function changed the name of its na-dot-rm argument to something else like remove_missing, your code would automatically still work.
The downside is that maybe that isn't what you want. Since a change of argument name could break code written by your users, perhaps you'd rather the change just broke your code so you could decide how to handle it. All in all, whether it's better to use dot-dot-dot here or not depends upon how much you trust the inner function, and how stable you need your signature to be.
Finally, dot-dot-dot isn't as clear to users, since they'd have to read the documentation for the inner function to know what to type.
7. Let's practice!
Since there are pros and cons of each method, let's try them both.