How can we create a nested function in R
Overview
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:
- Calling a function within another function we created.
- Writing a function within another function.
Calling a function within another function
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:
Code example
# 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))
Code explanation
-
Line 2: We creatd a function with two parameter values,
xandy. -
Line 4: The function we created tells
xto multiplyyand assign the output to a variablea. -
Line 5: We return the value of
a. -
Line 9: We make the first input
myFunction(2,2)represent the primary function’sxparameter. Likewise, we make the second inputmyFunction(3,3)represent theyparameter of the main function.
Hence, we get the following expected output:
(2 * 2) * (3 * 3) = 36
Writing a function within another function
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)
Code explanation
-
Line 2: We create an outer function,
outerFunction, and pass a parameter valuexto the function. -
Line 4: We create an inner function,
innerFunction, and pass a parameter valueyto the function. -
Line 6: We pass a command to the inner function, which tells
xto multiplyyand assign the output to a variablea. -
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
outputand give it a value of3. -
Line 13: We print the
outputwith the desired value of5as the value of theyparameter.
Therefore, the output is:
(3 * 5 = 15)