Functions in R Programming – The Complete Guide

A function is an organized and reusable code block that performs a specified activity within a program. Functions let users write cleaner, more efficient code by reducing repetition and improving readability. They help to expedite processes, improve debugging, and simplify changes, making R programming more approachable and manageable, even for complex computations.

In R, functions can be classified into two major types:

    • In-built functions: Predefined functions are available in the R environment to simplify jobs and improve coding productivity.
    • User-defined functions: These are custom functions built by the user to execute certain tasks, providing more freedom and control over computations.

In this article, we will look at the syntax, types, and implementation of R functions, as well as provide examples to help both beginners and advanced users understand how to use them effectively.

Table of Contents

What is Functions in R?

A function in R is a reusable piece of code that completes a certain task. It accepts input (arguments), processes them, and returns an output. Functions assist in creating modular and efficient programming. Combining logic behind functions allows developers to eliminate redundancy, improve readability, and make their code more manageable.

1. Syntax of Functions in R

function_name <- function(arguments) {
# Function body
return(output)
}
    • FunctionName: The name given to the function.
    • Arguments: Inputs passed to the function. Functions can take zero, one, or more arguments.
    • Function Body: Contains the code that performs the required task.
    • Return Value: The output generated by the function. Some functions may not return a value, but rather conduct operations such as printing outputs or altering global variables.

Types of Functions in R

Functions in R can be classified according to how they are used and defined. The following are the primary types of functions in R:

1. Built-in Functions

R provides several built-in functions for common tasks including mathematical operations, statistical analysis, and data processing.

Examples of Built-in Functions

x <- c(1, 2, 3, 4, 5)

print(sum(x))                                     # Sum of elements (Output: 15)
print(mean(x))                                   # Mean of elements (Output: 3)
print(median(x))                                # Median (Output: 3)
print(sd(x))                                        # Standard deviation
print(sort(x, decreasing = TRUE))         # Sorting in descending order

Common built-in function categories:

    • Mathematical functions: sum(), mean(), sd(), sqrt()
    • Statistical functions: var(), cor(), quantile()
    • String functions: paste(), tolower(), toupper()
    • Date functions: Sys.Date(), as.Date()
    • Data manipulation: subset(), merge(), aggregate()

2. User-defined Functions

User-defined functions enable adjustments to fulfill particular programming requirements. These functions are built by users and can handle a wide range of tasks. Users can define their own functions by using the function() keyword.

Examples of User-Defined Functions for Squaring Numbers

square <- function(x) {
return(x^2)
}

print(square(4)) # Output: 16

3. Lambda Functions

Lambda Functions or Anonymous functions are those functions which are not assigned a variable name. These are functions without a name, often used within functions like apply().

Example of Lambda Function in R

result <- sapply(1:5, function(x) x^2)

print(result) # Output: 1 4 9 16 25

How to Create a Function in R

Let’s see how we can create functions in R using some easy examples.

1. Creating a Simple Function that adds two numbers

add_numbers <- function(a, b) {
sum <- a + b
return(sum)
}

# Calling the function
result <- add_numbers(5, 7)
print(result) # Output: 12

2. Function Without Arguments

A function can be created without arguments.

greet <- function() {
print("Hello, welcome to R programming!")
}

# Calling the function
greet()

3. Function with Default Arguments

You can assign default values to arguments.

multiply <- function(a = 2, b = 3) {
return(a * b)
}

print(multiply()) # Uses default values (2 * 3 = 6)
print(multiply(4, 5)) # Uses provided values (4 * 5 = 20)

4. Function with Multiple Return Values

A function can return multiple values using a list.

calculate <- function(x, y) {
sum_val <- x + y
prod_val <- x * y
return(list(sum = sum_val, product = prod_val))
}

result <- calculate(4, 5)
print(result$sum) # Output: 9
print(result$product) # Output: 20

5. Creating a Recursive Function

A function that calls itself is called a recursive function. Here is how you can find the factorial of a number using recursive function

factorial_recursive <- function(n) {
if (n == 0) return(1)
return(n * factorial_recursive(n - 1))
}

print(factorial_recursive(5)) # Output: 120

6. Nested Functions

A function can contain another function.

outer_function <- function(x) {
inner_function <- function(y) {
return(y^2)
}
return(inner_function(x) + 10)
}

print(outer_function(3)) # Output: 19

7. Function as an Argument (Higher-Order Function)

A function can accept another function as an argument.

apply_function <- function(func, x) {
return(func(x))
}

square <- function(x) x^2
print(apply_function(square, 5)) # Output: 25

8. Custom Infix Functions

R allows defining custom infix functions.

"%multiply%" <- function(a, b) {
return(a * b)
}

print(3 %multiply% 4) # Output: 12

Conclusion

Creating functions in R improves code reuse and structure. Understanding different types of functions, default parameters, recursion, and higher-order functions will help you build more efficient and modular R code. If you want to learn more about similar topics, then do check out our Data Science Course today!

Our Data Science Courses Duration and Fees

Program Name
Start Date
Fees
Cohort Starts on: 4th May 2025
₹69,027
Cohort Starts on: 27th Apr 2025
₹69,027
Cohort Starts on: 13th Apr 2025
₹69,027

About the Author

Principal Data Scientist

Meet Akash, a Principal Data Scientist with expertise in advanced analytics, machine learning, and AI-driven solutions. With a master’s degree from IIT Kanpur, Aakash combines technical knowledge with industry insights to deliver impactful, scalable models for complex business challenges.