Escrever funções

R intermediário

Filip Schouwenaars

DataCamp Instructor

Quando escrever a sua?

  • Resolver um problema específico e bem definido
  • Princípio da caixa preta
  • Se funciona, o que acontece por dentro importa menos
R intermediário

A função triple()

R intermediário

A função triple()

my_fun <- function(arg1, arg2) {
  body
}
R intermediário

A função triple()

triple <- function(arg1, arg2) {
  body
}
R intermediário

A função triple()

triple <- function(x) {
  body
}
R intermediário

A função triple()

triple <- function(x) {
  3 * x
}
R intermediário

A função triple()

triple <- function(x) {
  3 * x
}
ls()
"triple"
triple(6)
18
  • O número 6 corresponde ao argumento x (por posição)
  • O corpo da função é executado: 3 * 6
  • Última expressão = valor de retorno
R intermediário

return()

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

A função math_magic()

R intermediário

A função math_magic()

R intermediário

A função math_magic()

R intermediário

A função math_magic()

my_fun <- function(arg1, arg2) {
  body
}
R intermediário

A função math_magic()

math_magic <- function(arg1, arg2) {
  body
}
R intermediário

A função math_magic()

math_magic <- function(a, b) {
  body
}
R intermediário

A função 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 intermediário

Argumento opcional

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

Usar return()

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

Vamos praticar!

R intermediário

Preparing Video For Download...