Introduction
Functions are reusable blocks of code that perform specific tasks. They are essential for writing modular and maintainable R code.
Creating Functions
# Simple function
greet <- function() {
print("Hello, World!")
}
greet()
# Function with parameter
greet_name <- function(name) {
paste("Hello,", name)
}
greet_name("Alice")
# Function with default parameter
greet_name <- function(name = "World") {
paste("Hello,", name)
}
greet_name()
Return Values
# Using return()
add <- function(a, b) {
return(a + b)
}
# Last expression is returned
add <- function(a, b) {
a + b # Returns automatically
}
Multiple Parameters
# Multiple parameters
calculate <- function(a, b, operation = "add") {
switch(operation,
"add" = a + b,
"sub" = a - b,
"mul" = a * b,
"div" = a / b
)
}
calculate(10, 5, "add")
Variable Scope
# Global vs local variables
x <- 10
test_scope <- function() {
y <- 5 # Local variable
print(x) # Access global
print(y)
x <<- 20 # Modify global
}
test_scope()
print(x)
Anonymous Functions
# Anonymous function
(function(x) x^2)(5)
# Apply anonymous function
sapply(1:5, function(x) x^2)
Summary
Functions are fundamental to R programming. Create well-documented functions for reusable code.