Psaní funkcí

Intermediate R

Filip Schouwenaars

DataCamp Instructor

Kdy psát vlastní funkci?

  • Řešení konkrétního, jasně definovaného problému
  • Princip černé skříňky
  • Pokud funguje, vnitřní implementace není zásadní
Intermediate R

Funkce triple()

Intermediate R

Funkce triple()

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

Funkce triple()

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

Funkce triple()

triple <- function(x) {
  body
}
Intermediate R

Funkce triple()

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

Funkce triple()

triple <- function(x) {
  3 * x
}
ls()
"triple"
triple(6)
18
  • Číslo 6 přiřazeno argumentu x (podle pozice)
  • Tělo funkce je vykonáno: 3 * 6
  • Poslední výraz = návratová hodnota
Intermediate R

return()

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

Funkce math_magic()

Intermediate R

Funkce math_magic()

Intermediate R

Funkce math_magic()

Intermediate R

Funkce math_magic()

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

Funkce math_magic()

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

Funkce math_magic()

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

Funkce 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
Intermediate R

Nepovinný argument

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

Použití return()

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

Pojďme si procvičit!

Intermediate R

Preparing Video For Download...