Functions in R
Functions in R are reusable blocks of code that perform a specific task. They help in organizing code, avoiding repetition, and making programs modular and easier to maintain.
Defining a Function
Functions in R are defined using the function
keyword. You can define a function with or without parameters.
# Function without parameters
greet <- function() {
return("Hello, World!")
}
print(greet())
# Function with parameters
greet_name <- function(name) {
return(paste("Hello,", name))
}
print(greet_name("Alice"))
Returning Values
Functions can return values using the return
keyword. If no return statement is provided, the function returns the value of the last expression.
add <- function(a, b) {
return(a + b)
}
result <- add(5, 10)
print(result) # Output: 15
# Implicit return
multiply <- function(a, b) {
a * b
}
print(multiply(3, 4)) # Output: 12
Default Arguments
You can provide default values for function arguments. If the caller does not provide a value, the default is used.
greet <- function(name = "Guest") {
return(paste("Hello,", name))
}
print(greet()) # Output: Hello, Guest
print(greet("Alice")) # Output: Hello, Alice
Variable-Length Arguments
Functions can accept a variable number of arguments using the ...
syntax.
sum_all <- function(...) {
sum(...)
}
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(1, 2, 3, 4, 5)) # Output: 15
Anonymous Functions
Anonymous functions (also called lambda functions) are functions without a name. They are often used for short, throwaway functions.
# Anonymous function
square <- function(x) x^2
print(square(5)) # Output: 25
# Using anonymous function with lapply
numbers <- 1:5
squared_numbers <- lapply(numbers, function(x) x^2)
print(squared_numbers) # Output: 1 4 9 16 25
Recursion
A function can call itself, which is known as recursion. Recursion is useful for solving problems like factorial calculation.
factorial <- function(n) {
if (n == 0 || n == 1) {
return(1)
}
return(n * factorial(n - 1))
}
print(factorial(5)) # Output: 120
Scope of Variables
Variables defined inside a function have local scope, meaning they can only be accessed within the function. Variables defined outside functions have global scope.
x <- 10 # Global variable
my_function <- function() {
y <- 5 # Local variable
print(paste("Local variable y:", y))
print(paste("Global variable x:", x))
}
my_function()
# print(y) # Error: y is not defined outside the function
Function Documentation
You can document your functions using comments. This helps others understand the purpose and usage of the function.
# Function to add two numbers
# Parameters:
# a: First number
# b: Second number
# Returns:
# The sum of a and b
add <- function(a, b) {
return(a + b)
}
print(add(3, 5)) # Output: 8
Next: Data Frames