[R] return inconsistency?
Ben Bolker
bbo|ker @end|ng |rom gm@||@com
Wed Apr 30 15:12:50 CEST 2025
Since R evaluates arguments 'greedily', it will evaluate the return()
component (and return from the function) without even seeing the second
component.
This example might clarify things:
f <- function(x) { return(x)/stop("bad!") }
> f(1)
[1] 1
Also possibly useful:
lobstr::ast(return(OR^2+6*OR+1)/(OR*se^2))
█─`/`
├─█─return
│ └─█─`+`
│ ├─█─`+`
│ │ ├─█─`^`
│ │ │ ├─OR
│ │ │ └─2
│ │ └─█─`*`
│ │ ├─6
│ │ └─OR
│ └─1
└─█─`(`
└─█─`*`
├─OR
└─█─`^`
├─se
└─2
On 2025-04-30 9:06 a.m., Duncan Murdoch wrote:
> `return` is a function. I am away from my computer right now so I can't
> check, but I would expect you could create your own function named that.
> Other languages have `return` statements instead.
>
> On Wed, Apr 30, 2025, 02:17 Ralf Goertz via R-help <r-help using r-project.org>
> wrote:
>
>> I made a stupid error when programming a function. I used
>>
>>> return(OR^2+6*OR+1)/(OR*se^2)
>>
>> Being parenthesis blind it took me half an hour to find the reason for
>> the nonsensical results I got. I should have written
>>
>>> return((OR^2+6*OR+1)/(OR*se^2))
>>
>> Having said that why is the first variant (which returns the value of
>> the numerator only) not a syntax error? I would have expected R to
>> report something like
>>
>>> Error: unexpected '/' in "return(OR^2+6*OR+1)/"
>>
>> If this is not an error what is its purpose?
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> https://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Dr. Benjamin Bolker
Professor, Mathematics & Statistics and Biology, McMaster University
Director, School of Computational Science and Engineering
> E-mail is sent at my convenience; I don't expect replies outside of
working hours.
More information about the R-help
mailing list