R Nested Functions

R Tutorial

 R Nested Functions

Nested functions in R mean defining a function inside another function.

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:

25

 Explanation:

  • outer() takes argument x

  • Inside it, inner() is defined

  • inner() squares its argument (y * y)

  • outer() calls inner(x)

  • outer(5)inner(5)5 * 525


 3. Accessing Outer Function Variables


 

Output:

15

 Explanation:

  • outer(5) → so x = 5

  • inner(10) is called → so y = 10

  • Inside inner()x + y5 + 10

  • Result = 15


4. Nested Function with Multiple Operations

 Output:

$sum
[1] 9
$difference
[1] 1
$product
[1] 20
$quotient
[1] 0.8

 Explanation:

  • add() → 4 + 5 = 9

  • subtract() → 4 – 5 = -1

  • multiply() → 4 × 5 = 20

  • divide() → 4 ÷ 5 = 0.8


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:

20
  •  Inner x does not change outer x

 7. Using <<- in Nested Functions (Advanced)


 

Output:

20
  • <<- modifies the outer variable
  •  Use carefully

 8. Returning a Nested Function (Closure)

Output:

[1] 16
[1] 64

 Explanation:

  • power_fn(n) returns a function

  • That returned function calculates x ^ n

  • square <- power_fn(2) → creates a function for power 2

  • cube <- power_fn(3) → creates a function for power 3

  • square(4) → 4² = 16

  • cube(4) → 4³ = 64

This is a perfect example of closure in R (function returning another function).

 

Nested Functions vs Normal Functions

FeatureNested FunctionNormal Function
ScopeLocalGlobal
AccessibilityInside parent onlyAnywhere
Use caseHelper logicReusable 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

You may also like...