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

Spencer Graves spencer.graves at structuremonitoring.com
Sun Jul 27 20:12:54 CEST 2014


On 7/27/2014 10:34 AM, William Dunlap wrote:
> This is a real hack, but you can redefine return in your function:
>> f <- function() {
> +     return("early return")
> +     "last value in function"
> + }
>> f()
> [1] "early return"
>> f <- function() {
> +     return <- function(x)x
> +     return("early return")
> +     "last value in function"
> + }
>> f()
> [1] "last value in function"
>
> IMO, well written functions do not have return statements in them.  They
> are the equivalent of goto statements.


       Is that a fortune or something hotly contested?


       I can understand the sentiment, and I'd like to know if there is 
research behind this?  I understand that "goto" was eliminated from 
modern languages precisely because research indicated it was a major 
source of problems.  This may seem related, but I'd like to see the data 
if anyone knows of such.  I've used "return" in the middle of functions 
to avoid an extra "else" layer after an "if". This may not be smart. 
I'd like to know how stupid it is ;-)


       Thanks for the comment.


       Spencer

> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
>
>
> On Sun, Jul 27, 2014 at 6:41 AM, super <desolator88 at 163.com> wrote:
>> Suppose that I had a function as below:
>> f<-function() {
>> return(1)
>> }
>> i want to change the body of f  to the form like this:
>> f<-function(){
>> 1
>> function() {}
>> }
>> How can i do the task using body(f) or something else solutions?
>>          [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.


-- 
Spencer Graves, PE, PhD
President and Chief Technology Officer
Structure Inspection and Monitoring, Inc.
751 Emerson Ct.
San José, CA 95126
ph:  408-655-4567
web:  www.structuremonitoring.com



More information about the R-help mailing list