Functions in R

📘 Introduction

A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you can define a function once and call it whenever needed. Functions improve code organization, reduce repetition, and make programs easier to understand and maintain.

Information

R provides many built-in functions such as print(), sum(), mean(), and sqrt(). You can also create your own functions using the function() keyword.

đŸŽ¯ Why Use Functions?

  • Reduce code duplication.
  • Improve program readability.
  • Organize code into reusable modules.
  • Simplify debugging and maintenance.
  • Encourage code reusability.

📚 Types of Functions in R

Functions
Built-in Functions
User-Defined Functions
Anonymous Functions

🔹 Built-in Functions

Built-in functions are predefined functions provided by R for performing common tasks.

Using Built-in Functions

numbers <- c(10, 20, 30, 40)

print(sum(numbers))
print(mean(numbers))
print(max(numbers))
print(min(numbers))
print(length(numbers))

Output

Console Output

[1] 100
[1] 25
[1] 40
[1] 10
[1] 4

📝 Creating a User-Defined Function

Use the function() keyword to define your own function.

Syntax of a Function

function_name <- function(parameters) {
  # Function body

  return(value)
}

Creating a Simple Function

greet <- function() {
  print("Welcome to R Programming!")
}

greet()

Output

Console Output

[1] "Welcome to R Programming!"

đŸ“Ĩ Function Parameters

Parameters allow values to be passed into a function, making it more flexible and reusable.

Function with Parameters

greet <- function(name) {
  print(paste("Hello", name))
}

greet("Alice")
greet("Bob")

Output

Console Output

[1] "Hello Alice"
[1] "Hello Bob"

📤 Returning Values

The return() function sends a value back to the function call. If return() is omitted, R automatically returns the value of the last evaluated expression.

Returning a Value

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

result <- square(6)

print(result)

Output

Console Output

[1] 36

đŸ”ĸ Function with Multiple Parameters

Addition Function

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

print(add(10, 20))
print(add(15, 35))

Output

Console Output

[1] 30
[1] 50

âš™ī¸ Default Parameter Values

Parameters can have default values, making them optional during function calls.

Default Parameters

greet <- function(name = "Guest") {
  print(paste("Welcome", name))
}

greet()
greet("Sophia")

Output

Console Output

[1] "Welcome Guest"
[1] "Welcome Sophia"

🔄 Anonymous Functions

Anonymous functions are functions without a name. They are often used with functions such as lapply(), sapply(), and apply().

Anonymous Function

numbers <- c(1, 2, 3, 4)

result <- sapply(numbers, function(x) x^2)

print(result)

Output

Console Output

[1]  1  4  9 16

🔁 Nested Function Calls

Functions can call other functions to perform complex tasks.

Nested Functions

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

cube_of_square <- function(x) {
  square(x)^3
}

print(cube_of_square(2))

Output

Console Output

[1] 64

📊 Variable Scope

Variables created inside a function are local variables and exist only within that function. Variables created outside a function are global variables.

Local and Global Variables

message <- "Global Variable"

showMessage <- function() {
  message <- "Local Variable"
  print(message)
}

showMessage()

print(message)

Output

Console Output

[1] "Local Variable"
[1] "Global Variable"

🧮 Real-World Example

The following function calculates the simple interest based on principal, rate, and time.

Simple Interest Calculator

simpleInterest <- function(principal, rate, time) {

  interest <- (principal * rate * time) / 100

  return(interest)
}

result <- simpleInterest(10000, 8, 2)

print(result)

Output

Console Output

[1] 1600

📊 Function Execution Flow

Define Function
Call Function
Pass Arguments
Execute Function Body
Return Result
Continue Program

📋 Built-in vs User-Defined Functions

FeatureBuilt-in FunctionUser-Defined Function
Created ByR DevelopersProgrammer
AvailabilityAlready availableMust be created before use
PurposeGeneral tasksCustom tasks
Examplessum(), mean()add(), simpleInterest()

âš ī¸ Common Mistakes

MistakeExplanationSolution
Calling a function before defining itThe function does not exist yet.Define the function before calling it.
Passing the wrong number of argumentsResults in an error or unexpected behavior.Match the function parameters correctly.
Ignoring variable scopeLocal variables are inaccessible outside the function.Understand the difference between local and global variables.
Writing overly complex functionsMakes code difficult to maintain.Keep functions short and focused on one task.

💡 Best Practices

  • Give functions meaningful and descriptive names.
  • Write functions that perform one specific task.
  • Use parameters instead of hard-coded values.
  • Include comments for complex logic.
  • Reuse functions whenever possible instead of duplicating code.

Best Practice

Well-designed functions make programs modular, reusable, and easier to test. Breaking large problems into smaller functions leads to cleaner and more maintainable R code.

📝 Summary

Functions are reusable blocks of code that perform specific tasks in R. You learned how to use built-in functions, create user-defined functions, pass parameters, return values, define default arguments, use anonymous functions, understand variable scope, and build modular programs. Mastering functions is an essential step toward writing organized, efficient, and reusable R code for both simple scripts and large applications.

>>"Functions turn repeated code into reusable solutions, making programs simpler, cleaner, and easier to maintain."