Open jdhoffa opened 4 years ago
In most cases, one does not need to use ‘return()’ at all in function blocks. R automatically, or more properly “lazily”, returns the value of the last expression evaluated. Honestly, I prefer to not use ‘return()’ statements unless they’re necessary for some reason, which is rarely the case.
The answer to the StackOverflow question, I think, is that the ‘return()’ statement is evaluated within the context/environment of the dplyr chain, so ironically if they simply remove the print statement at the end of the function, it would work as expected because of what I said above... the return would get gobbled up by the dplyr chain, the dplyr chain would evaluate, then the function would lazily return the last value of the last evaluated statement (the dplyr chain).
Ya, in the case that inspired this post, it was helpful to have a return() nested in an if statement, to end the function prematurely.
And I was confused because the statement after was throwing an error, that I thought the previous if statement should have dealt with
Great example of when a ‘return()’ is necessary. Thanks
R behaves strangely when you pipe a
return()
call.https://stackoverflow.com/questions/59596950/strange-behaviour-when-piping-to-return-in-r-function
https://github.com/tidyverse/magrittr/issues/32
Easiest just to save the result of the pipe to an output, and return that.