Return in R - r - learn r - r programming



  • Many times, we require our functions to do some processing and return back the result.
  • This is done with the return() function in R.
  • In other words transmit a value back to the caller by explicitly calling return().
  • Without this call, the value of the last executed statement will be returned by default.
 r-return

Syntax

return(expression)
  • The value returned from a function can be any valid object.

Example

  • Here is an example which will return whether a given number is positive, negative or zero.
check <- function(x) {
if (x >0) {
       result <- "Positive"
   }
elseif (x <0) {
       result <- "Negative"
   }
else {
       result <- "Zero"
   }
return(result)
}

Here, given sample codes.

>check(1)
[1] "Positive"

>check(-10)
[1] "Negative"
>check(0)
[1] "Zero"

Functions without return()

  • If there are no explicit returns from a function, the value of the last evaluated expression is returned automatically in R.
  • For example, the following is equivalent to the above function.
check <- function(x) {
if (x >0) {
       result <- "Positive"
   }
elseif (x <0) {
       result <- "Negative"
   }
else {
       result <- "Zero"
   }
   result
}
  • We generally use explicit return() functions to return a value immediately from a function.
  • If it is not the last statement of the function, it will prematurely end the function bringing the control to the place from which it was called.
check <- function(x) {
if (x>0) {
return("Positive")
   }
elseif (x<0) {
return("Negative")
   }
else {
return("Zero")
   }
}
  • In the above example, if x > 0, the function immediately returns "Positive" without evaluating rest of the body.

Multiple Returns

  • The return() function can return only a single object. If we want to return multiple values in R, we can use a list (or other objects) and return it.
  • Following is an example.
multi_return<- function() {
my_list<- list("color" = "red", "size" = 20, "shape" = "round")
return(my_list) 
}
  • Here, we create a list my_list with multiple elements and return this single list.
> a <- multi_return()
>a$color
[1] "red"
>a$size
[1] 20
>a$shape
[1] "round"


Related Searches to Return in R