How to create a function in R
Overview
A function in R is a block of code that will only run when called. We can pass data known as parameters to a function, and the function can return data as a result.
Creating a function
To create a function in R, we simply use the function() keyword.
Code example
# creating a function # create a function with the name my_functionmy_function <- function() {print("Hello World!")}
Code explanation
In the code above, we created a function my_function after assigning it to the function() keyword to ensure that R stores the variable my_function as a function.
It is worth noting that the code above did not execute the command given in the function. This is because the function we created was not called in our code.
Calling a function
To call a function in R, we simply use the name of the function we created alongside a parenthesis. For example, we simply type my_function() to call the function (my_function) we created in the previous code.
Code example
# creating a function # create a function with the name my_functionmy_function <- function() {print("Hello World!")}# calling the function we created in order to execute its commandmy_function()
As can be seen from the output of the code we wrote, the command of the function was executed because we called the function.