Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r
function
communitycreator

How to create a function in R

Onyejiaku Theophilus Chidalu

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_function
my_function <- function() { 
  print("Hello World!")
}
Creating a function in R

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_function
my_function <- function() { 
  print("Hello World!")
}

# calling the function we created in order to execute its command 
my_function()
Creating and calling a function in R

As can be seen from the output of the code we wrote, the command of the function was executed because we called the function.

RELATED TAGS

r
function
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring