R Cheat Sheet (9): Functions

本节主要关注R中的函数、函数的参数,以及自定义二元运算符。

1. R中的函数

R中函数的特征为函数名加上括号,如:

> Sys.Date()
[1] "2015-05-09"

大多数R中的函数都有返回值,如上面Sys.Date() 函数没有输入参数,它根据系统环境返回当前时间;另一些函数会对输入的数据进行处理并返回结果,如使用mean() 求均值:

> mean(c(2, 4, 5))
[1] 3.666667

函数中最后一条R表达式的值会作为函数的返回值:

> boring_function <- function(x) {
+     x
+ }
> boring_function('My first function!')
[1] "My first function!"

也可以使用return 来进行返回,需要注意的是,return 后的返回值必须位于括号中:

> boring_function <- function(x) {
+     return(x)
+ }
> boring_function('My first function!')
[1] "My first function!"

直接键入函数名可以查看函数的源代码:

> boring_function
function(x) {
    return(x)
}

2. 函数的参数

2.1. 参数默认值

在编写函数时,可以在参数列表中为参数设置默认值,如果在调用函数时没有指定该参数,就会使用该默认值代替:

> remainder <- function(num, divisor = 2) {
+     num %% divisor
+ }
> remainder(5, 2)
[1] 1
> remainder(5)
[1] 1
> remainder(11, 5)
[1] 1

在调用函数时,可以显式地指明个别或者全部参数的值,可以按照任意顺序填写显式指明的参数:

> remainder(divisor = 11, num = 5)
[1] 5
> remainder(4, div = 2)
[1] 0

使用arg() 函数可以查看指定函数的参数:

> args(remainder)
function (num, divisor = 2) 
NULL

2.2. 使用函数作为参数

上面的例子相当于将函数remainder() 作为参数传递给了函数arg() ,在R中可以把函数作为参数进行传递。

> evaluate <- function(func, dat){
+     func(dat)
+ }
> evaluate(sd, c(1.4, 3.6, 7.9, 8.8))
[1] 3.514138

也可以使用匿名函数作为参数:

> evaluate(function(x){x+1}, 6)
[1] 7

2.3. 使用可变数量个参数

定义函数时,其所接受的参数的个数可以是不确定的,如paste() 函数,它的签名为:

paste (..., sep = " ", collapse = NULL)

其中的三个点 表示其可以接受的参数个数是可变的:

> paste("Programming", "is", "fun!")
[1] "Programming is fun!"

在编写自己的函数时,也可以使用 来传递可变数量的参数:

> telegram <- function(...){
+     paste("START", ..., "STOP")
+ }
> telegram("Good", "morning")
[1] "START Good morning STOP"

在函数中,可以对传递进来的 进行解析,从中取出所需要的数据:

> mad_libs <- function(...){
+     args <- list(...)
+     
+     place <- args[["place"]]
+     adjective <- args[["adjective"]]
+     noun <- args[["noun"]]
+     
+     paste("News from", 
+           place, 
+           "today where", 
+           adjective, 
+           "students took to the streets in protest of the new", 
+           noun, 
+           "being installed on campus.")
+ }
> mad_libs(place="Mars", adjective="concerned", noun="oxygenerator")
[1] "News from Mars today where concerned students took to the streets in protest of the new oxygenerator being installed on campus."

3. 自定义二元运算符

R也支持自定义二元运算符:

> "%p%" <- function(x, y){ # Remember to add arguments!
+     paste(x, y)
+ }
> "I" %p% "love" %p% "R!"
[1] "I love R!"