本节主要讲述R语言中的函数
基本的函数形式
例如写一个脚本,命名为remainder.R
,脚本内容为
remainder <- function(num, divisor = 2) {
# Write your code here!
# Remember: the last expression evaluated will be returned!
num %% divisor
}
在控制台下输入source('remainder.R')
,这时候就可以在控制台下调用remainder.R
文件里的函数。
> remainder(5)
[1] 1
> remainder(11, 5)
[1] 1
> remainder(divisor = 11, num = 5) # 顺序可以改,但是要指定好,跟python类似
[1] 5
> remainder(4, div = 2)
[1] 0
上面是四种调用方式,这里主要介绍一下最后一种,最后一种是参数前缀部分匹配即可,他会自动找到divisor
参数,不需要输入完整的参数也可以匹配到,但是要慎用。
可以通过之前介绍的函数args
来查看函数的参数
> args(remainder)
function (num, divisor = 2)
NULL
把函数当作参数来传递
函数内容如下:
evaluate <- function(func, dat){
# Write your code here!
# Remember: the last expression evaluated will be returned!
func(dat)
}
调用如下:
> evaluate(sum, c(1.4, 3.6, 7.9, 8.8))
[1] 21.7
> evaluate(function(x){x+1}, 6)
[1] 7
第二种调用方式有点类似python中的lambda
传递无限多参数
telegram <- function(...){
paste("START", ..., "STOP", collapse = " ")
}
调用
> telegram("hhaha", "hhhh", 'ssss')
[1] "START hhaha hhhh ssss STOP"
省略号的意思是传递的参数个数不限。
mad_libs <- function(...){
# Do your argument unpacking here!
args <- list(...) # unpack our parameters
place <- args[["place"]]
noun <- args[["noun"]]
adjective <- args[["adjective"]]
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="china", adjective="100", noun="USA")
[1] "News from china today where 100 students took to the streets in protest of the new USA being installed on campus."
自定义二元运算符
"%p%" <- function(args1, args2){ # Remember to add arguments!
paste(args1, args2, sep = " ")
}
调用二元运算符%p%
,
> 'I' %p% 'love' %p% 'R!'
[1] "I love R!"
自定义的二元运算符必须是如下形式:%[whatever]%
,旁边得加两个百分号。