From ec308d1a5e050a8ddeb32678746f400c3b031220 Mon Sep 17 00:00:00 2001 From: hadley Date: Wed, 2 Mar 2016 10:55:14 -0600 Subject: [PATCH] Discuss types of arguments --- functions.Rmd | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/functions.Rmd b/functions.Rmd index c414529..e4b3231 100644 --- a/functions.Rmd +++ b/functions.Rmd @@ -335,10 +335,24 @@ Neither `if` not `switch` are vectorised: they work with a single value at a tim ## Arguments - Note that arguments in R are lazily evaluated: they're not computed until they're needed. That means if they're never used, they're never called. This is an important property of R the programming language, but is unlikely to be important to you for a while. You can read more about lazy evaluation at -### Default arguments +Often the arguments to a function fall into two broad sets: one set supplies the data to compute on, and the other supplies arguments that controls the details of the computation. For example: + +* In `log()`, the data is `x`, and the base of the logarithm is `base`. + +* In `mean()`, the data is `x`, and `trim` and `na.rm` control the computation. + +* In `t.test()`, the data is `x` and `y`, and `alternative`, `mu`, `paired`, + `var.equal`, and `conf.level` control the details of the test. + +* In `paste()` you can supply unlimited strings to `...`, and the pasting + is controlled by `sep` and `collapse`. + +Generally, the arguments that control computation have default values so you don't need to supply the most commonly used values. + +In almost all cases, the default value should be the value that is used most commonly. There are a few exceptions to do with safety. For example, `na.rm` should always have default value `FALSE` even though `TRUE` is what you usually want if you have missing values. The default forces you to confront and deal with the missingness in your data, rather than allowing it to silently propagate. + You can choose to supply default values to your arguments for common options. This is useful so that you don't need to repeat yourself all the time.