R Nested Functions

Nested functions in R are functions defined within other functions. They are useful for structuring code logically and encapsulating functionality that is only relevant within a particular scope.

Key Topics

Nested Function Example

# Example of a nested function
outer_function <- function(x) {
    inner_function <- function(y) {
        return(y * 2)
    }
    result <- inner_function(x) + 5
    return(result)
}

# Calling the outer function
outer_function(3)

Output:

[1] 11

Code Explanation: The outer_function defines a nested inner_function that doubles the input value. The outer_function calls inner_function with x and adds 5 to the result before returning it.

Scope Behavior

In R, nested functions have access to the variables in their parent function's scope. However, variables defined in the nested function are not accessible outside of it.

Key Takeaways

  • Nested functions are useful for encapsulating functionality within a specific scope.
  • They can access variables from the parent function but cannot be accessed outside their defining function.
  • Using nested functions can help organize and modularize code.