What is the body() function in R?

Overview

In R, the body() function is used to set or get the body of a function.

Syntax

The syntax for getting the body of a function using the body() function:

body(fun = sys.function(sys.parent()))

The syntax for setting the body of a function:

body(fun, envir = environment(fun)) <- value

Parameters

The body() function takes the following parameter values:

  • fun: This represents the function object.
  • envir: This represents the environment in which the function should be defined.
  • value: This represents the value to make up the value of the function.

Return value

This function returns the body of the specified function.

Example of getting:

# creating a function
myfunction <- function(x) x^5
# getting the body of the function
function_body <- body(myfunction )
# printing the body of the function
function_body

Explanation

  • Line 2: We create a function and assign it to a variable myfunction.

  • Line 5: We implement the body() function and the result is assigned to a variable function_body.

  • Line 8: We print the variable function_body.

Example of setting:

# creating a function
f <- function(x) x^5
function_body <- body(f) <- quote(5^x)
function_body

Explanation

  • Line 3: We use the body() function to change the body of the function from x^5 to 5^x.

Free Resources