Return Value from R Function

• Last Updated : 23 Dec, 2021

In this article, we will discuss how to return value from a function in R Programming Language.

Method 1: R function with return value

In this scenario, we will use the return statement to return some value

Syntax:

function_name <- function(parameters) {

statements

return(value)

}

function_name(values)

Where,

• function_name is the name of the function
• parameters are the values that are passed as arguments
• return() is used to return a value
• function_name(values) is used to pass values to the parameters

Example: R program to perform addition operation with return value

Output:

 30

Method 2: R function without using return

Here without using return function we will return a value. For this just passing the name of the variable that stores the value to returned works.

Syntax:

function_name <- function(parameters) {

statements

value

}

function_name(values)

where,

• function_name is the name of the function
• parameters are the values that are passed as arguments
• value is the return value
• function_name(values) is used to pass values to the parameters

Example: R program to perform addition operation without using return function

Output:

 30

Method 3: R function to return multiple values as a list

In this scenario, we will use the list() function in the return statement to return multiple values.

Syntax:

function_name <- function(parameters) {

statements

return(list(value1,value2,.,value n)

}

function_name(values)

where,

• function_name is the name of the function
• parameters are the values that are passed as arguments
• return() function tales list of values as input
• function_name(values) is used to pass values to the parameters

Example: R program to perform arithmetic operations and return those values

R

 # define arithmetic function# perform arithmetic operations on two valuesarithmetic = function(val1,val2) {        # add       add=val1+val2     # subtract  sub=val1-val2     # multiply  mul=val1*val2   # divide  div=val2/val1     # return the result as a list  return(list(add,sub,mul,div))} # pass the values to the functionarithmetic(10,20)

Output:

[]
 30

[]
 -10

[]
 200

[]
 2

My Personal Notes arrow_drop_up