Returning from a Function
In this lesson, we will learn how to return a value from a function in R.
The return()
Function
Let’s take an example: finding the maximum number between two numbers.
maxNumber <- function(myNumber1, myNumber2)
{
if(myNumber1 > myNumber2)
{
print(myNumber1)
} else
{
print(myNumber2)
}
}
Here, we are printing the maximum number. Now, suppose instead of printing the maximum number our program needs to perform some task with the maximum number. Therefore, instead of printing, we want the function maxNumber
to give us the number, i.e., return the maximum number so that we can use it.
This is where the function return()
comes in handy.
Syntax of return()
Function
return(expression)
The value returned from a
function
can be any valid object.
We can simply return the maximum number and the program calling the function can receive it.
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy