To create a user-defined function in R, we use the keyword function
and the following syntax:
function_name <- function(parameters){
function body
}
Powered By
- Function name—the name of the function object that will be used for calling the function after its definition.
- Function parameters—the variables separated with a comma and placed inside the parentheses that will be set to actual argument values each time we call the function.
- Function body—a chunk of code in the curly brackets containing the operations to be performed in a predefined order on the input arguments each time we call the function. Usually, the function body contains the
return()
statement (or statements) that returns the function output, or theprint()
statement (or statements) to print the output.
An example of a simple user-defined function in R:
my_function <- function(x, y){
return(x + y)
}
Leave a Reply