- R Programming By Example
- Omar Trejo Navarro
- 257字
- 2021-07-02 21:30:38
Operators are functions
Now that you have a working understanding of how functions work. You should know that not all function calls look like the ones we have shown so far, where you use the name of the function followed by parentheses that contains the function's arguments. Actually, all statements in R, including setting variables and arithmetic operations, are functions in the background, even if we mostly call them with a different syntax.
Remember that previously in this chapter we mentioned that R objects could be referred to by almost any string, but you should avoid doing so. Well here we show how using cryptic names can be useful under certain contexts. The following example shows how the assignment, selection, and addition operators are usually used with sugar syntax (a term used to describe syntax that exists for ease of use), but that in the background they use the functions named [<-, [, and +, respectively.
The [<-() function receives three arguments: the vector we want to modify, the position we want to modify in the vector, and the value we want it to have at that position. The [() function receives two arguments, the vector from which we want to retrieve a value and the position of the value we want to retrieve. Finally, the +() function receives the two values we want to add. The following example shows the syntax sugar, followed by the background function calls R performs for us:
x <- c(1, 2, 3, 4, 5)
x
#> [1] 1 2 3 4 5
x[1] <- 10
x
#> [1] 10 2 3 4 5
`[<-`(x, 1, 20)
#> [1] 20 2 3 4 5
x
#> [1] 10 2 3 4 5
x[1]
#> [1] 10
`[`(x, 1)
#> [1] 10
x[1] + x[2]
#> [1] 12
`+`(x[1], x[2])
#> [1] 12
`+`(`[`(x, 1), `[`(x, 1))
#> [1] 20
In practice, you would probably never write these statements as explicit function calls. The syntax sugar is much more intuitive and much easier to read. However, to use some of the advanced techniques shown in this book, it is helpful to know that every operation in R is a function.
- Verilog HDL數(shù)字系統(tǒng)設(shè)計入門與應(yīng)用實例
- 機器人智能運動規(guī)劃技術(shù)
- VMware Performance and Capacity Management(Second Edition)
- 嵌入式操作系統(tǒng)
- Statistics for Data Science
- 云計算和大數(shù)據(jù)的應(yīng)用
- 網(wǎng)絡(luò)脆弱性掃描產(chǎn)品原理及應(yīng)用
- Mastering Ansible(Second Edition)
- Java求職寶典
- 從機器學(xué)習(xí)到無人駕駛
- 百度智能小程序:AI賦能新機遇
- fastText Quick Start Guide
- 隨機分布控制系統(tǒng)的故障診斷與容錯控制
- ABB工業(yè)機器人虛擬仿真教程
- Linux應(yīng)用程序設(shè)計