Reputation: 1696
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:")
return(sum1)
sum2 <- y+z
print("The second sum is:")
return(sum2)
}
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?
Thanks.
Upvotes: 0
Views: 63
Reputation: 3274
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.
Upvotes: 1
Reputation: 992
myFun <- function(x,y,z){
sum1 <- x+y
print("The first sum is:")
sum2 <- y+z
print("The second sum is:")
return(sum2)
}
return(variable) returns the variable and exits. Try the above one.
Upvotes: 1