

固定参数函数
f1 <- function(a,b=2){
message(a,b)
return(a+b) # 没有return返回最后一条语句
}
b <- f1(5) # 52
b # 7
f1(2,5) # 25
f1(b=2,a=5) # 52
f1(b=5,2) # 25
可变参数的函数
r自带函数 c(..., recursive = FALSE, use.names = TRUE)
f2 <- function(...){
cat(..2) # 2
dot_args = list(...)
print(dot_args)
}
f2(1,2,3,4,5)
一切都是对象
操作符也是函数类型对象
1+2 # 3
"+"(1,2) # 3
`+`(1,2) # 3
'+'(1+2) # 3
'<-'(new_var,5)
new_var # 5
':'(1,5) # 1 2 3 4 5
'['(1:10,2) # 2
自定义运算符
'%ab2c%' <- function(a,b){
sqrt(sum(a^2,b^2))
}
ab2c(3,4)
3 %ab2c% 4
'ab2c' <- function(a,b){
sqrt(sum(a^2,b^2))
}
ab2c(3,4)
3 %ab2c% 4
ab2c <- function(a,b){
sqrt(sum(a^2,b^2))
}
ab2c(3,4)
3 %ab2c% 4
5+2 # 7
"+" <- function(x,y){
x*y
}
5+2 # 10
rm(`+`)
5+2 # 7
对于%>%的理解
library(purrr)
x <- c(1,1,2,2,8,5,9)
x %>%
unique() %>%
sort()
# > 1 2 8 5 9
x <- unique(x)
x <- sort(x)
# > 1 2 8 5 9
泛型和多态
函数接受不同的对象有不同的结果‘
x <- seq(1,100,by=10)
y <- 2*x + 10
xy <- cbind(x,y)
class(xy) # matrix
plot(xy,
xlim = c(1,100),
ylim = c(0,230),
type = "o",col="red") # figure 1
x <- seq(1,100,by=10)
y <- 2*x + 10
xy <- cbind(x,y)
my_model <- lm(y~x)
class(my_model) # lm
op <- par(mfrow = c(2,2))
plot(my_model) # figure 2
par(op)

figure 1

figure 2
自定义泛型函数
my_function <- function(x,y){
message("I am interface")
UseMethod("my_function",x) # 通过x标签类型确定执行函数
}
my_function.addXY <- function(x,y){
return(x+y)
}
my_function.multiplyXY <- function(x,y){
return(x*y)
}
my_function.default <- function(x,y){
return(x-y)
}
x<-9
y<-5
my_function(x,y) # default 4
class(x) <- "addXY"
my_function(x,y) # addXY 14
class(x) <- "multiplyXY"
my_function(x,y) # multiplyXY 45
对于泛型函数"+"的理解
"+" 是有两个参数函数的操作
"+.onlyFirst" <- function(a,b){
return(a[1]+b[1])
}
a <- 1:5
b <- 6:10
a+b # 7 9 11 13 15
"+"(a,b) # 7 9 11 13 15
class(a) <- "onlyFirst"
a+b # 7
"+"(a,b) # 7
class(a) <- NULL
class(b) <- "onlyFirst"
a+b # 7
"+"(a,b) # 7
class(a) <- "onlyFirst"
class(b) <- "onlyFirst"
a+b # 7
"+"(a,b) # 7
R递归
fun1 <- function(s){
message("before",s)
if(s>0){
fun1(s-1)
}
message("after",s)
}
fun1(5)
before5
before4
before3
before2
before1
before0
after0
after1
after2
after3
after4
after5
递归Fibonacci
fib <- function(n){
if(n==1){
return(1)
}else{
return(c(fib(n-1),sum(fib(n-1),n=2)))
}
}
fib(10)
# > 1 3 6 12 24 48 96 192 384 768