Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

functions
r
communitycreator

How can we create a nested function in R

Onyejiaku Theophilus Chidalu

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:

  1. Calling a function within another function we created.
  2. 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 parameters
myFunction <- function(x, y) {
  # passing a command to the function
  a <- x * y
  return(a)
}

# creating a nested function
myFunction(myFunction(2,2), myFunction(3,3))

Code explanation

  • 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

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 function
outerFunction <- function(x) {
  # creating an inner function
  innerFunction <- function(y) {
    # passing a command to the function
    a <- x * y
    return(a)
  }
  return (innerFunction)
}
# To call the outer functionn
output <- outerFunction(3) 
output(5)

Code explanation

  • 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)

RELATED TAGS

functions
r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring