In R, the body()
function is used to set or get the body of a function.
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
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.This function returns the body of the specified function.
# creating a functionmyfunction <- function(x) x^5# getting the body of the functionfunction_body <- body(myfunction )# printing the body of the functionfunction_body
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
.
# creating a functionf <- function(x) x^5function_body <- body(f) <- quote(5^x)function_body
body()
function to change the body of the function from x^5
to 5^x
.