How to create a user-defined function in R?

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 
  1. Function name—the name of the function object that will be used for calling the function after its definition.
  2. 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.
  3. 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 the print() 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)
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *