Chapter 5 Functions
Basic function
= function () {
foo 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
= function (x) {
addOne return(x + 1)
}addOne(5)
#> [1] 6
The syntax for return is like a function: return(value)
Parameter order can be arbitrary
= function (x, y) {
add 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.
= 5
a = function (a) {
foo = 6
a 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)
= 5
a = function () {
foo = 6
a = 100
b 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
= function (a, b) {
foo = function(x) {
square 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
= function (a, b) {
foo return (a / b)
}= function(a, ...) {
bar 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