撰寫函式

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 中級

一起來練習吧!

R 中級

Preparing Video For Download...