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

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.

主站蜘蛛池模板: 黄平县| 新竹市| 余姚市| 金山区| 赣州市| 晋城| 白银市| 云林县| 德钦县| 南昌市| 罗山县| 耒阳市| 宜良县| 临漳县| 睢宁县| 郯城县| 天门市| 衡阳市| 泰州市| 来凤县| 淮北市| 巨鹿县| 葵青区| 丹棱县| 枣庄市| 仪征市| 特克斯县| 五峰| 裕民县| 白玉县| 易门县| 滨州市| 广丰县| 开远市| 蓬莱市| 福贡县| 东阳市| 色达县| 岐山县| 嘉峪关市| 子洲县|