0
0
R Programmingprogramming~5 mins

Return values in R Programming

Choose your learning style9 modes available
Introduction

Return values let a function send back a result after it finishes running. This helps you use that result later in your program.

When you want a function to calculate something and give you the answer.
When you need to reuse the result of a function in other parts of your code.
When you want to keep your code organized by separating tasks into functions.
When you want to check or store the output of a function for further use.
Syntax
R Programming
function_name <- function(arguments) {
  # do some work
  return(value)
}

The return() function sends the value back to where the function was called.

If you don't use return(), R returns the last evaluated expression automatically.

Examples
This function adds two numbers and returns the sum.
R Programming
add <- function(x, y) {
  return(x + y)
}
This function returns the square of a number without using return(). R returns the last line automatically.
R Programming
square <- function(x) {
  x * x
}
This function creates a greeting message and returns it.
R Programming
greet <- function(name) {
  message <- paste("Hello," , name)
  return(message)
}
Sample Program

This program defines a function that multiplies two numbers and returns the result. Then it calls the function with 4 and 5, stores the result, and prints it.

R Programming
multiply <- function(a, b) {
  result <- a * b
  return(result)
}

output <- multiply(4, 5)
print(output)
OutputSuccess
Important Notes

Using return() makes your code clearer, especially for beginners.

Functions can return any type of value: numbers, text, vectors, or even other functions.

Summary

Return values let functions send results back to the caller.

Use return() to specify what to send back, or rely on R's automatic return of the last expression.

Returned values can be saved and used later in your program.