A function is a highly organized block of code that only executes when it is explicitly called.
Functions allow you to write complex code once, and reuse it thousands of times across your application!
To create a function in R, you use the function() keyword.
You must assign the newly created function to a variable securely using the <- operator.
To execute the function, you simply call its variable name followed by parentheses ().
# Defining the function
my_function <- function() {
print("Hello World from my custom function!")
}
# Executing the function
my_function()
Functions become incredibly powerful when you pass custom data into them.
Information can be securely passed into functions as arguments!
Arguments are specified strictly inside the parentheses when defining the function.
my_function <- function(fname) {
print(paste(fname, "Doe"))
}
my_function("Peter")
my_function("Lois")
To let a function return a calculated result, use the return() function.
This securely sends the final data back to the script so you can store it in a new variable!
Which keyword is strictly required to create a custom function in R?
What function securely passes data back out from inside a custom function?