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

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.

主站蜘蛛池模板: 台中市| 云南省| 新闻| 大邑县| 安徽省| 黔东| 临桂县| 门头沟区| 霞浦县| 泸州市| 于都县| 渝北区| 南京市| 扎囊县| 扬州市| 怀安县| 保山市| 北辰区| 延边| 江西省| 如东县| 高安市| 修水县| 方山县| 宁海县| 高阳县| 白朗县| 青铜峡市| 涿鹿县| 宿迁市| 句容市| 巴彦县| 吉林市| 锦州市| 承德市| 秦皇岛市| 西丰县| 天气| 天长市| 黄龙县| 大余县|