R Functions
A function is a named block of code that runs only when it is called. The same function can be called many times.
Defining runs nothing
The definition stores the function and runs nothing inside it. The print before the call appears first and the greeting inside appears second.
say_hello <- function() {
print("Hello from inside")
}
print("Before the call")
say_hello()The last value comes back
This function multiplies its input by two. The call with 4 gives back 8.
double <- function(num) {
num * 2
}
print(double(4))A function that prints
This function prints a greeting built from its input. The call with Ana shows Hello Ana.
greet <- function(name) {
print(paste("Hello", name))
}
greet("Ana")Example
add_five <- function(num) {
num + 5
}
print(add_five(10))
print(add_five(3))Key points
- The function keyword starts a function definition.
- The definition is stored in a name with <-.
- Curly braces hold the block of code that runs on each call.
- Defining a function runs nothing inside the block.
- Calling a function runs its block once.
- The last value in the block is the value the call gives back.
- A function can also just print a result and give back nothing visible.
In this example, add_five takes one number and gives back that number plus five. The two calls show the same block working on two different inputs.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What happens right after a function is defined?