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
# define addition function # perform addition operation on two values addition= function (val1,val2) {
# add
add=val1+val2
# return the result
return (add)
} # pass the values to the function 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
# define addition function # perform addition operation on two values addition= function (val1,val2) {
# add
add=val1+val2
# return the result with out using return
add
} # pass the values to the function 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
# define arithmetic function # perform arithmetic operations on two values arithmetic = 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 function arithmetic (10,20)
|
Output:
[[1]] [1] 30 [[2]] [1] -10 [[3]] [1] 200 [[4]] [1] 2