R Programming By Example
上QQ阅读APP看书,第一时间看更新

Optional arguments

When creating functions, you may specify a default value for an argument, and if you do, then the argument is considered optional. If you do not specify a default value for an argument, and you do not specify a value when calling a function, you will get an error if the function attempts to use the argument.

In the following example, we show that if a single numeric vector is passed to our l2_norm() function as it stands, it will throw an error, but if we redefine it to make the second vector optional, then we will simply return the first vector's norm, not the distance between two different vectors To accomplish this, we will provide a zero-vector of length one, but because R repeats vector elements until all the vectors involved in an operation are of the same length, as we saw before in this chapter, it will automatically expand our zero-vector into the appropriate dimension:

l2_norm(a)     # Should throw an error because `y` is missing
#> Error in l2_norm(a): argument "y" is missing, with no default l2_norm <- function(x, y = 0) sum((x - y)^2) l2_norm(a) # Should work fine, since `y` is optional now #> [1] 14 l2_norm(a, b) # Should work just as before
#> [1] 27

As you can see, now our function can optionally receive the y vector, but will also work as expected without it. Also, note that we introduced some comments into our code. Anything that comes after the # symbol in a line, R will ignore, which allows us to explain our code where need be. I prefer to avoid using comments because I tend to think that code should be expressive and communicate its intention without the need for comments, but they are actually useful every now and then.