[R-pkg-devel] Native pipe in package examples

Serguei Sokol @ergue|@@oko| @end|ng |rom gm@||@com
Fri Jan 26 10:31:42 CET 2024


Le 25/01/2024 à 19:04, Berwin A Turlach a écrit :
> On Thu, 25 Jan 2024 09:44:26 -0800
> Henrik Bengtsson <henrik.bengtsson using gmail.com> wrote:
> 
>> On Thu, Jan 25, 2024 at 9:23 AM Berwin A Turlach
>> <berwin.turlach using gmail.com> wrote:
>>>
>>> G'day Duncon,
> 
> Uups, apologies for the misspelling of your name Duncan.  Fingers were
> too fast. :)
> 
> [...]
>>> But you could always code your example (not tested :-) ) along lines
>>> similar to:
>>>
>>> if( with(version, all(as.numeric(c(major, minor)) >= c(4, 1))) ){
>>>    ## code that uses native pipe
>>> }else{
>>>    cat("You have to upgrade to R >= 4.1.0 to run this example\n")
>>> }
>>
>> That will unfortunately not work in this case, because |> is part of
>> the new *syntax* that was introduced in R 4.1.0.  Older versions of R
>> simply doesn't understand how to *parse* those two symbols next to
>> each other, e.g.
>>
>> {R 4.1.0}> parse(text = "1:3 |> sum()")
>> expression(1:3 |> sum())
>>
>> {R 4.0.5}> parse(text = "1:3 |> sum()")
>> Error in parse(text = "1:3 |> sum()") : <text>:1:6: unexpected '>'
>> 1: 1:3 |>
>>           ^
>>
>> In order for R to execute some code, it needs to be able to parse it
>> first. Only then, it can execute it.  So, here, we're not even getting
>> past the parsing phase.
> 
> Well, not withstanding 'fortune(181)', you could code it as:
> 
> if( with(version, all(as.numeric(c(major, minor)) >= c(4, 1))) ){
>     cat(eval(parse(text="1:3 |> sum()")), "\n")
> }else{
>    cat("You have to upgrade to R >= 4.1.0 to run this example\n")
> }
> 
By nitpicking a little bit, this test won't work for v5.0 as minor "0" 
is less then "1". There are a more canonical ways to test the version 
and send a message (or a 'warning()'):

if (getVersion() >= "4.1") {
    cat(eval(parse(text="1:3 |> sum()")), "\n")
} else {
    message("You have to upgrade to R >= 4.1.0 to run this example")
}

Best,
Serguei.



More information about the R-package-devel mailing list