Pragyaditya Das Pragyaditya Das - 5 months ago 24
R Question

Multiple returns in the same function

I am trying to display two results inside the same function, the code that I am writing is as follows:

myFun <- function(x,y,z){
sum1 <- x+y
print("The first sum is:")

sum2 <- y+z
print("The second sum is:")


However, I only get the sum1 as the output. After that, the sum2 block is never executed.

The result I got is :

> myFun(2,3,4)
[1] "The first sum is:"
[1] 5

What am I doing wrong? Can somebody help me out?



Copied from my comment above

The first return breaks out of the function. If you want to execute and return both statements, only use one return statement at the end, such as return(list(sum1, sum2)) or to print, return f(paste, sum1, sum2) where f is just some function which defines the print return format.