Home » Functions in R

Functions in R

Functions are one of the core building blocks of programming in R. They are used to encapsulate a sequence of statements that perform a specific task, making the code reusable, organized, and efficient. In R, almost everything is a function, even fundamental operations like addition (+) or printing output (print()).

What is a Function?

A function in R is a block of code designed to perform a particular task. Functions take inputs (arguments), perform computations, and return outputs.

Syntax of a Function:

function_name <- function(arguments) {
# Function body (code to execute)
return(output)
}

Example:

add_numbers <- function(a, b) {
sum <- a + b
return(sum)
}
add_numbers(5, 3) # Output: 8

Types of Functions in R

1. Built-in Functions: R comes with a rich library of pre-defined functions.

Examples:

  • mean(): Computes the mean of a vector.
  • summary(): Provides a summary of an object.
  • plot(): Creates various types of plots.

2. User-Defined Functions: These are functions created by users to address specific needs or repetitive tasks.

Example:

square <- function(x) {
return(x^2)
}
square(4) # Output: 16

3. Anonymous Functions: Functions without names are called anonymous functions. They are often used inside other functions like apply() or lapply().

Example:

sapply(1:5, function(x) x^2) # Output: 1 4 9 16 25

Special-Purpose Functions:
These functions are tailored for specific tasks or domains, like statistical analysis or visualization.

Examples:

lm() for linear models, ggplot() for advanced graphics.

Purpose of Functions

Functions serve multiple purposes:

  • Code Reusability: Write once and use the function multiple times.
  • Simplification: Break down complex problems into smaller, manageable tasks.
  • Readability: Functions make the code easier to understand and debug.
  • Encapsulation: Keeps the logic separate, reducing errors.

Concepts Related to Functions

1. Arguments:

  • Functions accept inputs called arguments, which can have default values.
  • Example

greet <- function(name = “User”) {
paste(“Hello,”, name)
}
greet(“John”) # Output: “Hello, John”
greet() # Output: “Hello, User”

2. Formal vs Actual Arguments:

  • Formal arguments: Defined in the function’s declaration.
  • Actual arguments: Provided when the function is called.

3. Return Values:

  • Functions return outputs explicitly using the return() function or implicitly by the last evaluated expression.

cube <- function(x) {
x^3 # Implicit return
}
cube(2) # Output: 8

4. Scope of Variables:

Variables created inside a function have local scope and are not accessible outside the function.

Functions vs Expressions and Objects

  • Functions: Perform actions and encapsulate logic.
  • Expressions: Represent computations (e.g., 5 + 3).
  • Objects: Hold data or results (e.g., variables created by function outputs).