Nested functions in R are like having a recipe within a recipe. You create one function inside another function. It's useful when you have a task that can be broken down into smaller tasks, and those smaller tasks are only needed within the context of the larger task.
Let's illustrate this with a simple example of a function that calculates the area of a rectangle, and within it, we have another function to calculate the perimeter of the rectangle:
Example
# Define a function to calculate the area of a rectangle
calculate_area <- function(length, width) {
# Nested function to calculate the perimeter
calculate_perimeter <- function(length, width) {
perimeter <- 2 * (length + width)
return(perimeter)
}
# Calculate the area
area <- length * width
# Call the nested function to calculate the perimeter
perimeter <- calculate_perimeter(length, width)
# Print both area and perimeter
cat("Area:", area, "\n")
cat("Perimeter:", perimeter, "\n")
}
# Now let's use the calculate_area function
calculate_area(5, 3)
In this example:
calculate_area
that takes length
and width
as parameters to calculate the area of a rectangle.calculate_area
, we define another function calculate_perimeter
, which takes length
and width
as parameters to calculate the perimeter of the rectangle. This function is nested inside calculate_area
.length
and width
.calculate_perimeter
to calculate the perimeter.Nested functions are helpful for encapsulating related logic within a function, making your code more modular and easier to understand.