Chapter 5 Functions

Basic function

foo = function () {
  print("hello world")
}
foo()
#> [1] "hello world"

Note: in the function, you need to use print to output

5.1 Parameters

Parameters and return values

addOne = function (x) {
  return(x + 1)
}
addOne(5)
#> [1] 6

The syntax for return is like a function: return(value)

Parameter order can be arbitrary

add = function (x, y) {
  return(x + (y*10))
}
add(x=2, y=10)
#> [1] 102
add(y=10, x=2)
#> [1] 102

Functions are vectorized by default

addOne(1:5)
#> [1] 2 3 4 5 6

All parameters are pass-by-value because functions are immutable.

a = 5
foo = function (a) {
  a = 6
  print(paste("Inside the function as a parameter: ", a))
}
print(paste("Before the function: ", a))
#> [1] "Before the function:  5"
foo(1)
#> [1] "Inside the function as a parameter:  6"
print(paste("After the function: ", a))
#> [1] "After the function:  5"

5.2 Scope

When you assign a value inside a function, it creates a local variable in the scope of the function. You can’t access the global variable inside the function. (OK, you can, but the syntax is so obnoxious that I pretend it doesn’t exist)

a = 5
foo = function () {
  a = 6
  b = 100
  print(paste("Inside the function a =", a))
  print(paste("Inside the function b =", b))
}
print(paste("Before the function a =", a))
#> [1] "Before the function a = 5"
foo()
#> [1] "Inside the function a = 6"
#> [1] "Inside the function b = 100"
print(paste("After the function a =", a))
#> [1] "After the function a = 5"
#trying to use `b` here will cause an error because it is out of scope

5.3 A function in a function

Might be useful for encapsulation

foo = function (a, b) {
  square = function(x) {
    return(x ^ x)
  }
  print(c(a, b))
  print(c(square(a), square(b)))
}
foo(1, 10)
#> [1]  1 10
#> [1] 1e+00 1e+10

5.4 Dot dot dot

foo = function (a, b) {
  return (a / b)
}
bar = function(a, ...) {
  return(foo(a, ...))
}
bar(50, 10)
#> [1] 5
bar(b = 10, 50) # named parameter works too
#> [1] 5

5.5 Operators

Operators like + or - or even [ are all functions. To use them like a function, surround them with `.

`+`(3, 4)
#> [1] 7
`*`(3, 4)
#> [1] 12
`[`(5:10, 2) # you don't need the close bracket ]
#> [1] 6