A nested function or the enclosing function is a function that is defined within another function. In simpler words, a nested function is a function in another function.
There are two ways to create a nested function in the R programming language:
For this process, we have to create the function with two or more required parameters. After that, we can call the function that we created whenever we want to. Let’s look at the code given below to better understand this:
# creating a function with two parametersmyFunction <- function(x, y) {# passing a command to the functiona <- x * yreturn(a)}# creating a nested functionmyFunction(myFunction(2,2), myFunction(3,3))
Line 2: We creatd a function with two parameter values, x
and y
.
Line 4: The function we created tells x
to multiply y
and assign the output to a variable a
.
Line 5: We return the value of a
.
Line 9: We make the first input myFunction(2,2)
represent the primary function’s x
parameter. Likewise, we make the second input myFunction(3,3)
represent the y
parameter of the main function.
Hence, we get the following expected output:
(2 * 2) * (3 * 3) = 36
In this process, we can’t directly call the function because there is an inner function defined inside an outer function. Therefore, we will call the external function to call the function inside. Let’s look at the code given below to better understand this:
# creating an outer functionouterFunction <- function(x) {# creating an inner functioninnerFunction <- function(y) {# passing a command to the functiona <- x * yreturn(a)}return (innerFunction)}# To call the outer functionnoutput <- outerFunction(3)output(5)
Line 2: We create an outer function, outerFunction
, and pass a parameter value x
to the function.
Line 4: We create an inner function, innerFunction
, and pass a parameter value y
to the function.
Line 6: We pass a command to the inner function, which tells x
to multiply y
and assign the output to a variable a
.
Line 7: We return the value of a
.
Line 9: We return the innerFunction
.
Line 12: To call the outer function, we create a variable output
and give it a value of 3
.
Line 13: We print the output
with the desired value of 5
as the value of the y
parameter.
Therefore, the output is:
(3 * 5 = 15)