 # return() Function In R Language: Syntax And Code example In this article, you’ll learn how to return a value from a function in R language. You’ll also discover how to employ functions that don’t have a return function. We will frequently need our functions to perform some processing and provide the output. This is performed in R language by using the return() function

To better understand this function, follow the article below.

## The syntax of return() function in R

### The Syntax: return one a value

functionName <- function(arguments) {
# Body code
return(expression)
}

functionName(val)
• functionName: The name of the function.
• arguments: The parameters are passed.
• expression: The value or any valid objects can be returned by a function.
• functionName(val): Return the value pass values to the arguments.

### The Syntax: return multiples value as a list

functionName <- function(arguments) {
# Body code
return(list(val_1,val_2,.,val_n))
}

functionName(val)
• functionName: The name of the function.
• arguments: The parameters are passed.
• expression: The value or any valid objects can be returned by a function.
• functionName(val): Return the value pass values to the arguments.

## The example of return() function in R

Here, we will refer to 3 examples: return a value, multiple values, and without value.

### Return one value

# Function with return one value
mean <- function(num1,num2){

# Calculate the mean value
m <- (num1 + num2) / 2

# Return the result
return(m)
}

mean(4,5)
mean(6,8)

Output

 4.5
 7

The function only returns one result: the product of 4 and 5 or 6 and 8.

### Return multiple values as a list

The code below demonstrates how to write a function that returns multiple values:

# Function with multiple values
calc <- function(x, y, z){
addition = x + y + z

# Multiplication
mulp = x * y * z

}

calc(5,8,6)

Output

[]
 19

[]
 240

Note: We returned two values in this example, but you may use a similar syntax to return as many values as you like with the return() option.

### Return a value without using return

# Function with multiple values
calc <- function(x, y, z){

addition = x + y + z

# Return result of the function
}

calc(5,8,6)

Output

 19

## Summary

This article will show you how to use the return() function in R language. I hope you find the information in this post beneficial. If you have any troubles, please post a comment. I’ll react. Thank you for reading, and best wishes!

Maybe you are interested:

Posted in R