- 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.
- Practical Data Analysis
- Google Cloud Platform Cookbook
- 人工免疫算法改進(jìn)及其應(yīng)用
- PIC單片機(jī)C語(yǔ)言非常入門(mén)與視頻演練
- VB語(yǔ)言程序設(shè)計(jì)
- Maya極速引擎:材質(zhì)篇
- 基于Xilinx ISE的FPAG/CPLD設(shè)計(jì)與應(yīng)用
- 單片機(jī)C語(yǔ)言應(yīng)用100例
- 網(wǎng)站入侵與腳本攻防修煉
- AMK伺服控制系統(tǒng)原理及應(yīng)用
- 機(jī)器學(xué)習(xí)案例分析(基于Python語(yǔ)言)
- 新一代人工智能與語(yǔ)音識(shí)別
- 新世紀(jì)Photoshop CS6中文版應(yīng)用教程
- 多媒體技術(shù)應(yīng)用教程
- OSGi原理與最佳實(shí)踐