[R] How to modify the body of a function?

Spencer Graves spencer.graves at prodsyse.com
Mon Jul 28 02:22:41 CEST 2014


On 7/27/2014 4:29 PM, MacQueen, Don wrote:
> As long as people are sharing their preferences . . .
>
>
> I find return() useful in a scenario like the following:
>
> Myfun <- function() {
>    {a few lines of code}
>    if (condition) return(whatever)
>    {Many, many lines of code}
>    Results
> }
>
> Which I find preferable to
>
> Myfun <- function() {
>    { a few lines of code}
>    if (condition) {
>      Results <- something
>    } else {
>      {Many, many lines of code}
>      Results <- something.else
>    }
>    Results
> }
>
>
>
> It is the presence of those many lines of code which separate the opening
> and closing brackets after the else that make the former easier to read
> and understand (again in my opinion).


       Thanks for the comment.  I prefer that style, also.


       However, I'm also sympathetic to  Bill Dunlap's opinion that, 
"They are the equivalent of goto statements." I was hoping to elicit a 
response from someone with a reference to a study suggesting that "  if 
(condition) return(whatever)" is either better than, equivalent to, or 
worse than "if ... else".  I can easily change my preference on this if 
research supports Dunlap and Newmiller against you, Bert Gunter, and me.


       Spencer

> I guess this is more along the lines of exception handling.
>
> Also note that this is something of a special case; I don¹t in general
> advocate using return().
>



More information about the R-help mailing list