编写函数

R 中级

Filip Schouwenaars

DataCamp Instructor

何时自己编写?

  • 解决一个明确的特定问题
  • 黑箱原则
  • 只要能用,内部细节不重要
R 中级

triple() 函数

R 中级

triple() 函数

my_fun <- function(arg1, arg2) {
  body
}
R 中级

triple() 函数

triple <- function(arg1, arg2) {
  body
}
R 中级

triple() 函数

triple <- function(x) {
  body
}
R 中级

triple() 函数

triple <- function(x) {
  3 * x
}
R 中级

triple() 函数

triple <- function(x) {
  3 * x
}
ls()
"triple"
triple(6)
18
  • 数值 6 按位置匹配到参数 x
  • 执行函数体:3 * 6
  • 最后一个表达式 = 返回值
R 中级

return()

triple <- function(x) {
  y <- 3 * x
  return(y)
}
triple(6)
18
R 中级

math_magic() 函数

R 中级

math_magic() 函数

R 中级

math_magic() 函数

R 中级

math_magic() 函数

my_fun <- function(arg1, arg2) {
  body
}
R 中级

math_magic() 函数

math_magic <- function(arg1, arg2) {
  body
}
R 中级

math_magic() 函数

math_magic <- function(a, b) {
  body
}
R 中级

math_magic() 函数

math_magic <- function(a, b) {
  a*b + a/b
}
math_magic(4, 2)
10
math_magic(4)
Error: argument "b" is missing, with no default
R 中级

可选参数

math_magic <- function(a, b = 1) {
  a*b + a/b
}
math_magic(4)
8
math_magic(4, 0)
Inf
R 中级

使用 return()

math_magic <- function(a, b = 1) {
  if(b == 0){
    return(0)
  }
  a*b + a/b
}
math_magic(4, 0)
0
R 中级

Ayo berlatih!

R 中级

Preparing Video For Download...