Return Value from R Function
Last Updated :
12 May, 2022
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
R
addition= function (val1,val2) {
add=val1+val2
return (add)
}
addition (10,20)
|
Output:
[1] 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
R
addition= function (val1,val2) {
add=val1+val2
add
}
addition (10,20)
|
Output:
[1] 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 takes 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
arithmetic = function (val1,val2) {
add=val1+val2
sub=val1-val2
mul=val1*val2
div=val2/val1
return ( list (add,sub,mul,div))
}
arithmetic (10,20)
|
Output:
[[1]]
[1] 30
[[2]]
[1] -10
[[3]]
[1] 200
[[4]]
[1] 2
Share your thoughts in the comments
Please Login to comment...