官术网_书友最值得收藏!

  • R Programming By Example
  • Omar Trejo Navarro
  • 283字
  • 2021-07-02 21:30:38

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.

主站蜘蛛池模板: 伊金霍洛旗| 靖远县| 石城县| 遵义市| 锡林浩特市| 大余县| 龙陵县| 崇左市| 屏山县| 巴林左旗| 武平县| 讷河市| 民和| 库尔勒市| 饶河县| 陆良县| 广安市| 凤阳县| 北川| 岳普湖县| 嘉黎县| 明溪县| 四子王旗| 浪卡子县| 东丰县| 达孜县| 敖汉旗| 盐池县| 龙泉市| 彭山县| 民权县| 类乌齐县| 滦南县| 孟津县| 北川| 怀仁县| 桦甸市| 方城县| 古蔺县| 台中县| 大石桥市|