functionname<-function(arg1,arg2,...){ #functionname函数名字,arg1,...表示参数
do any code in here when called
return(returnobject) #遇到return语句函数自动退出并通过命令提示符给用户返回控制
}
> myfib <- function(){
+ fib.a <- 1
+ fib.b <- 1
+ cat(fib.a,", ",fib.b,", ",sep="")
+ repeat{
+ temp <- fib.a+fib.b
+ fib.a <- fib.b
+ fib.b <- temp
+ cat(fib.b,", ",sep="")
+ if(fib.b>150){
+ cat("BREAK NOW...")
+ break
+ }
+ }
+ }
> myfib()
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, BREAK NOW...
添加参数
> myfib2 <- function(thresh){
+ fib.a <- 1
+ fib.b <- 1
+ cat(fib.a,", ",fib.b,", ",sep="")
+ repeat{
+ temp <- fib.a+fib.b
+ fib.a <- fib.b
+ fib.b <- temp
+ cat(fib.b,", ",sep="")
+ if(fib.b>thresh){
+ cat("BREAK NOW...")
+ break
+ }
+ }
+ }
> myfib2(thresh=150)
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, BREAK NOW...
返回结果
> myfib3 <- function(thresh){
+ fibseq <- c(1,1)
+ counter <- 2
+ repeat{
+ fibseq <- c(fibseq,fibseq[counter-1]+fibseq[counter])
+ counter <- counter+1
+ if(fibseq[counter]>thresh){
+ break
+ }
+ }
+ return(fibseq)
+ }
> myfib3(150)
[1] 1 1 2 3 5 8 13 21 34 55 89 144 233
如果函数中没有return语句,执行到最后一行代码后,函数结束,将返回最近指派或创建的对象
> dummy1 <- function(){
+ aa <- 2.5
+ bb <- "string me along"
+ cc <- "string 'em up"
+ dd <- 4:8
+ }
> foo <- dummy1()
> foo
[1] 4 5 6 7 8
> dummy2 <- function(){
+ aa <- 2.5
+ bb <- "string me along"
+ cc <- "string 'em up"
+ dd <- 4:8
+ return(dd)
+ }
> bar <- dummy2()
> bar
[1] 4 5 6 7 8 #两次结果一样
函数遇到return命令后结束,不执行函数体剩下的代码
> dummy3 <- function(){
+ aa <- 2.5
+ bb <- "string me along"
+ return(aa)
+ cc <- "string 'em up"
+ dd <- 4:8
+ return(bb)
+ }
> baz <- dummy3()
> baz
[1] 2.5
惰性计算:与参数相关的重要概念,在表达式中只在被需要时被计算,适用于参数访问以及出现在函数体中
>multiples1 <- function(x,mat,str1,str2){
+ matrix.flags <- sapply(x,FUN=is.matrix) #x为矩阵,则返回TRUE
+ if(!any(matrix.flags)){ #判断如果x不为矩阵,则返回str1
+ return(str1)
+ }
+ #如果为矩阵函数不退出,继续执行
+ indexes <- which(matrix.flags) #索引值赋值
+ counter <- 0
+ result <- list()
+ for(i in indexes){
+ temp <- x[[i]]
+ if(ncol(temp)==nrow(mat)){
+ counter <- counter+1
+ result[[counter]] <- temp%*%mat
+ }
+ }
+
+ if(counter==0){
+ return(str2)
+ } else {
+ return(result)
+ }
+ }
函数检验
> multiples1(x=foo,mat=diag(2),str1="no matrices in 'x'",str2="matrices in 'x' but none of appropriate dimensions given 'mat'")
[[1]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
[[2]]
[,1] [,2]
[1,] 1 5
[2,] 2 6