R Nested Functions

R Nested Functions
The inner function is only accessible within the outer function.
This concept is closely related to scope and lexical scoping in R.
1. What is a Nested Function?
A function written inside another function
Inner function can use variables of the outer function
Improves encapsulation and code organization
2. Basic Nested Function Example
Output:
Explanation:
outer()takes argumentxInside it,
inner()is definedinner()squares its argument (y * y)outer()callsinner(x)outer(5)→inner(5)→5 * 5→ 25
3. Accessing Outer Function Variables
Output:
Explanation:
outer(5)→ sox = 5inner(10)is called → soy = 10Inside
inner()→x + y→5 + 10Result = 15
4. Nested Function with Multiple Operations
5. Why Use Nested Functions?
- Hide helper logic
- Avoid global namespace pollution
- Improve readability
- Maintain logical grouping of code
6. Scope Rules in Nested Functions
Output:
- Inner
xdoes not change outerx
7. Using <<- in Nested Functions (Advanced)
Output:
<<-modifies the outer variable- Use carefully
8. Returning a Nested Function (Closure)
Nested Functions vs Normal Functions
| Feature | Nested Function | Normal Function |
|---|---|---|
| Scope | Local | Global |
| Accessibility | Inside parent only | Anywhere |
| Use case | Helper logic | Reusable logic |
Summary
Nested functions are functions inside functions
Inner function can access outer variables
Helps in code organization and safety
Supports closures and functional programming
