[R] Operator proposal: %between%

Duncan Murdoch murdoch.duncan at gmail.com
Fri Sep 5 13:43:00 CEST 2014


On 05/09/2014, 6:47 AM, Torbjørn Lindahl wrote:
> I don't mind maintaining this, however I'm not creating a new util package
> just for one function, there are already several nice util libraries out
> there, adding one more adds to fragmentation more than this single function
> provides usefulness.
> 
> If anyone wants to adopt this low-maintenance-cost love child, that would
> be the best option. If this is something, worthy of R-Core I'd be happy to
> submit it, but from the sound of it that door seems closed. I think %>%
> etc. also should go there, they look great and would make everyday life
> simpler, almost enjoyable.
> 
> Also some of the point of this function is keeping it as an operator, that
> provides better readability and mental flow.
> 

Another issue with operators is that they have quite high operator
precedence, as mentioned in the TeachingDemos help page for %<%.  So for
example,

2 < 4
2 %<% 4
1 + 1 < 2 + 2

all return TRUE (in %<% with some attributes), but

1 + 1 %<% 2 + 2

returns 4, with attributes.  (It is evaluated as 1 + (1 %<% 2) + 2,
whereas the regular < has lower precedence, so it is evaluated as (1 +
1) < (2 + 2).

See the ?Syntax help page for the precedence rules.  Some languages
allow user-defined operators to be assigned a particular precedence, but
in R the precedence is fixed.  This means that user-defined operators
are less readable than you might think.

Duncan Murdoch

> Looks like all variations of between shown could easily be merged into one
> cover-it-all operator
> 
> T.
> 
> 
> On Fri, Sep 5, 2014 at 10:36 AM, Gabor Grothendieck <ggrothendieck at gmail.com
>> wrote:
> 
>> On Thu, Sep 4, 2014 at 10:41 AM, Torbjørn Lindahl 
>> <torbjorn.lindahl at gmail.com> wrote:
>>> Not sure if this is the proper list to propose changes like this, if it
>>> passes constructive criticism, it would like to have a %between% operator
>>> in the R language.
>>>
>>
>> There is a between function in the data.table package.
>>
>>> library(data.table)
>>> between
>> function (x, lower, upper, incbounds = TRUE)
>> {
>>     if (incbounds)
>>         x >= lower & x <= upper
>>     else x > lower & x < upper
>> }
>>
>> and also in the tis package which works differently:
>>
>>> library(tis)
>>> between
>> function (y, x1, x2)
>> {
>>     y <- unclass(y)
>>     x1 <- unclass(x1)
>>     x2 <- unclass(x2)
>>     small <- pmin(x1, x2)
>>     large <- pmax(x1, x2)
>>     (y >= small) & (y <= large)
>> }
>>
>> In addition, SQL has a between operator
>>
>>> library(sqldf)
>>> sqldf("select * from BOD where Time between 3 and 5")
>>   Time demand
>> 1    3   19.0
>> 2    4   16.0
>> 3    5   15.6
>>
> 
> 
>



More information about the R-help mailing list