No.7 自定义函数
一、自定义函数
1.定义函数
#定义函数 无参函数
myprint<-function(){
print("I like R!")
}
myprint()#调用函数
#定义函数 有参函数
myadd<-function(a,b){
print(paste("the first is",a))
print(paste("the first is",b))
return(a+b) #a+b
}
s<-myadd(a=11,b=12)
#定义函数 有参函数
myadd<-function(a,b){
print(paste("the first is",a))
print(paste("the first is",b))
a+b
}
s<-myadd(a=11,b=12)
2.返回值
#自定义函数返回函数体最后一行的代码执行,或者返回return值(return放在前面,return后面的语句不再执行)
3.匿名函数
一般用作其他函数的参数。
sapply(1:10,function(x){x^2})
这里没有定义函数名字,是对前面1到10 每个元素平方。
(function(x){x^2})(1:10)
c(1:10)^2
结果一样:
> sapply(1:10,function(x){x^2})
[1] 1 4 9 16 25 36 49 64 81 100
> (function(x){x^2})(1:10)
[1] 1 4 9 16 25 36 49 64 81 100
> c(1:10)^2
[1] 1 4 9 16 25 36 49 64 81 100


浙公网安备 33010602011771号