Functions in R allow you to encapsulate reusable code, making your scripts more organized, readable, and efficient. By writing your own functions, you can perform repetitive tasks without rewriting code.
1. Basic Function Structure
A function in R is defined using the function() keyword:
my_function <- function(arg1, arg2) {
# Code to execute
result <- arg1 + arg2
return(result)
}
Explanation:
my_functionis the name of the function.arg1,arg2are input arguments.return()specifies the output value of the function.
Calling a Function
my_function(5, 3) # Returns 8
2. Functions Without Return Statement
If you don’t use return(), R automatically returns the last evaluated expression:
add_numbers <- function(a, b) {
a + b
}add_numbers(4, 7) # Returns 11
3. Functions with Default Arguments
You can set default values for arguments:
greet <- function(name = "User") {
paste("Hello,", name)
}greet("Alice") # Returns "Hello, Alice"
greet() # Returns "Hello, User"
4. Functions with Multiple Operations
A function can contain multiple statements:
calculate_stats <- function(x) {
mean_value <- mean(x)
max_value <- max(x)
min_value <- min(x)
return(list(mean = mean_value, max = max_value, min = min_value))
}calculate_stats(c(5, 10, 15, 20))
Output: A list containing mean, max, and min values.
5. Using Functions Inside Other Functions
Functions can call other functions:
square <- function(x) { x^2 }
sum_of_squares <- function(a, b) {
square(a) + square(b)
}sum_of_squares(3, 4) # Returns 25
6. Advantages of Writing Functions
- Reuse code and reduce repetition
- Improve code readability and organization
- Simplify debugging and maintenance
- Make complex operations easier to manage
Conclusion
Writing functions in R is a powerful way to automate tasks, organize your code, and perform complex calculations efficiently. By mastering function creation, you can streamline your data analysis workflow and make your scripts modular, reusable, and professional.