Functions are fundamental building blocks in R programming. They allow you to encapsulate reusable code, making your programs more organized and efficient. This guide will introduce you to the basics of R functions.
In R, you can create a function using the following syntax:
function_name <- function(arg1, arg2, ...) {
# Function body
# Code to be executed
return(result)
}
Let's break down the components:
function_name
: The name you give to your functionfunction()
: Keyword to define a functionarg1, arg2, ...
: Function arguments (optional){ }
: Curly braces contain the function bodyreturn()
: Specifies the value to be returned (optional)Here's a basic function that adds two numbers:
add_numbers <- function(a, b) {
sum <- a + b
return(sum)
}
# Calling the function
result <- add_numbers(5, 3)
print(result) # Output: 8
Functions can have multiple arguments, including optional ones with default values. For more details on this topic, check out the guide on R Function Arguments.
Functions in R can return a single value or multiple values as a list or vector. The return()
statement is optional; R automatically returns the last evaluated expression. Learn more about R Return Values.
calculate_rectangle_area <- function(length, width = 5) {
area <- length * width
return(area)
}
# Calling the function
area1 <- calculate_rectangle_area(10) # Using default width
area2 <- calculate_rectangle_area(8, 6) # Specifying both arguments
print(area1) # Output: 50
print(area2) # Output: 48
Understanding R function basics is crucial for writing efficient and organized code. As you progress, explore more advanced topics like R Functional Programming and R Apply Family of Functions to enhance your R programming skills.
Remember, practice is key to mastering functions in R. Experiment with different function structures and use cases to solidify your understanding.