Writing Functions

Intermediate R

Filip Schouwenaars

DataCamp Instructor

When write your own?

  • Solve a particular, well-defined problem
  • Black box principle
  • If it works, inner workings less important
Intermediate R

The triple() function

Intermediate R

The triple() function

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

The triple() function

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

The triple() function

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

The triple() function

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

The triple() function

triple <- function(x) {
  3 * x
}
ls()
"triple"
triple(6)
18
  • Numeric 6 matched to argument x (by pos)
  • Function body is executed: 3 * 6
  • Last expression = return value
Intermediate R

return()

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

The math_magic() function

Intermediate R

The math_magic() function

Intermediate R

The math_magic() function

Intermediate R

The math_magic() function

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

The math_magic() function

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

The math_magic() function

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

The math_magic() function

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

Optional argument

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

Use return()

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

Let's practice!

Intermediate R

Preparing Video For Download...