Functies schrijven

R voor gevorderden

Filip Schouwenaars

DataCamp Instructor

Wanneer zelf schrijven?

  • Los een specifiek, duidelijk probleem op
  • Zwartedoos-principe
  • Als het werkt, is de binnenkant minder belangrijk
R voor gevorderden

De functie triple()

R voor gevorderden

De functie triple()

my_fun <- function(arg1, arg2) {
  body
}
R voor gevorderden

De functie triple()

triple <- function(arg1, arg2) {
  body
}
R voor gevorderden

De functie triple()

triple <- function(x) {
  body
}
R voor gevorderden

De functie triple()

triple <- function(x) {
  3 * x
}
R voor gevorderden

De functie triple()

triple <- function(x) {
  3 * x
}
ls()
"triple"
triple(6)
18
  • Numeriek 6 gekoppeld aan argument x (op positie)
  • Functiebody wordt uitgevoerd: 3 * 6
  • Laatste expressie = returnwaarde
R voor gevorderden

return()

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

De functie math_magic()

R voor gevorderden

De functie math_magic()

R voor gevorderden

De functie math_magic()

R voor gevorderden

De functie math_magic()

my_fun <- function(arg1, arg2) {
  body
}
R voor gevorderden

De functie math_magic()

math_magic <- function(arg1, arg2) {
  body
}
R voor gevorderden

De functie math_magic()

math_magic <- function(a, b) {
  body
}
R voor gevorderden

De functie 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 voor gevorderden

Optioneel argument

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

Gebruik return()

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

Laten we oefenen!

R voor gevorderden

Preparing Video For Download...