R Tutorial
Fundamentals of R
Variables
Input and Output
Decision Making
Control Flow
Functions
Strings
Vectors
Lists
Arrays
Matrices
Factors
DataFrames
Object Oriented Programming
Error Handling
File Handling
Packages in R
Data Interfaces
Data Visualization
Statistics
Machine Learning with R
Functions are the foundational building blocks in R (and most programming languages) that allow you to encapsulate a sequence of operations into a single, reusable unit. Functions can simplify your code, make it more readable, and reduce errors. In this introductory tutorial, we'll cover the basics of creating and using functions in R.
A function is a self-contained block of code that encapsulates a specific task or related group of tasks. Functions typically take in some inputs (called "arguments"), process them, and return an output.
The basic structure of an R function looks like this:
function_name <- function(arg1, arg2, ...) { # Do something return(result) }
function_name
: Name of the function.arg1, arg2, ...
: Arguments of the function.return(result)
: The value that the function outputs. The return
statement is optional; if omitted, the function will return the result of the last evaluated expression.Here's an example of a basic function that adds two numbers:
add_numbers <- function(a, b) { sum <- a + b return(sum) } result <- add_numbers(5, 3) print(result) # Outputs: 8
You can set default values for your function arguments:
add_numbers <- function(a = 1, b = 1) { sum <- a + b return(sum) } print(add_numbers()) # Outputs: 2 print(add_numbers(5)) # Outputs: 6
The return()
statement is optional. If omitted, the function returns the last evaluated expression:
multiply_numbers <- function(a, b) { product <- a * b product # This value will be returned } print(multiply_numbers(5, 3)) # Outputs: 15
...
ArgumentThe ellipsis (...
) is used when the number of arguments is unknown:
print_all <- function(...) { args <- list(...) for (arg in args) { print(arg) } } print_all(1, "hello", TRUE)
Variables declared inside a function are local to that function and are not accessible outside:
test_function <- function() { local_var <- "I'm local!" print(local_var) } test_function() # print(local_var) # This would result in an error
Understanding functions is key to effective programming in R. As you work on more complex tasks, you'll find that creating your own functions is essential for maintaining clean, readable, and efficient code. As a best practice, when you find yourself writing similar code multiple times, consider if it can be encapsulated into a function.
Functions in R:
# Simple function in R greet <- function() { print("Hello, World!") } # Calling the function greet()
Creating functions in R:
# Creating a function in R square <- function(x) { return(x^2) } # Calling the function result <- square(5)
Returning values from functions in R:
return()
statement to return values from a function in R.# Returning values from a function in R add_numbers <- function(a, b) { result <- a + b return(result) } # Calling the function and capturing the result sum_result <- add_numbers(3, 5)
Nested functions in R:
# Nested functions in R outer_function <- function(x) { inner_function <- function(y) { return(x * y) } return(inner_function(3)) } # Calling the outer function result <- outer_function(2)
Anonymous functions in R:
function()
keyword without assigning a name.# Anonymous function in R multiply <- function(x, y) { return(x * y) } # Equivalent anonymous function anonymous_multiply <- function(x, y) x * y # Calling both functions result1 <- multiply(2, 3) result2 <- anonymous_multiply(2, 3)
Function closures in R:
# Function closure in R make_multiplier <- function(factor) { multiplier <- function(x) { return(x * factor) } return(multiplier) } # Creating and using a closure times_two <- make_multiplier(2) result <- times_two(5)