In past pages of notes we’ve seen and used many functions without seriously defining what functions are. A function is very similar to a mathematical function. A function may have some input and when a function is evaluated it either returns a value or it performs some task. In R you can define your own functions. Below I’ll define a very simple function that returns the number 3:
i_return_three <- function(){
3
}
i_return_three()
## [1] 3
The last expression of the function is evaluated and the resulting value is returned. The function i_return_three()
takes no arguments. Below I’ll illustrate a function that takes one argument:
add_one <- function(x){
x + 1
}
add_one(4)
## [1] 5
Arguments are variables that are defined within the context of the function. Variables that are defined outside of the function are ignored if they share the same name as function arguments. Here’s an example of what I’m taking about:
y <- 100
arg_y <- function(y) {
y + 1
}
arg_y(4)
## [1] 5
x <- 200
arg_x <- function(z){
x + 1
}
arg_x(30)
## [1] 201
You can define as many arguments for a function as you want:
add_x_y_z <- function(x, y, z){
x + y + z
}
add_x_y_z(3, 6, 9)
## [1] 18
You can also set default values for function arguments:
print_a_then_b <- function(a = "a", b = "b"){
print(a)
print(b)
}
print_a_then_b()
## [1] "a"
## [1] "b"
print_a_then_b("Hello", "World!")
## [1] "Hello"
## [1] "World!"
print_a_then_b("World!", "Hello") # it's me...
## [1] "World!"
## [1] "Hello"
If you explicity specify the value of arguments then the order of arguments doesn’t matter:
print_a_then_b(b = "This goes on the bottom", a = "This goes on top")
## [1] "This goes on top"
## [1] "This goes on the bottom"
If you’ve read through all of the notes for Lecture 1 then you should be able to complete these challanges:
%%
).