[Rd] [External] Re: should base R have a piping operator ?

Tierney, Luke |uke-t|erney @end|ng |rom u|ow@@edu
Mon Oct 7 18:17:46 CEST 2019


On Mon, 7 Oct 2019, Lionel Henry wrote:

>
>
>> On 7 Oct 2019, at 17:04, Tierney, Luke <luke-tierney using uiowa.edu> wrote:
>>
>>  Think about what happens if an
>> argument in a pipe stage contains a pipe. (Not completely
>> unreasonable, e.g. for a left_join).
>
> It should work exactly as it does in a local environment.
>
> ```
> `%foo%` <- function(x, y) {
>  env <- parent.frame()
>
>  # Use `:=` to avoid partial matching on .env/.frame
>  rlang::scoped_bindings(. := x, .env = env)
>
>  eval(substitute(y), env)
> }
>
> "A" %foo% {
>  print(.)
>  "B" %foo% print(.)
>  print(.)
> }
> #> [1] "A"
> #> [1] "B"
> #> [1] "A"
>
> print(.)
> #> Error in print(.) : object '.' not found
>
> ```
>
> The advantage is that side effects (such as assigning variables or calling
> `return()`) will occur in the expected environment.

You get the assignment behavior with the nested call approach. (Not
that doing this is necessarily a good idea).

> I don't see it causing
> problems except in artificial cases. Am I missing something?

Here is a stylized example:

f <- function(x, y) {
     assign("xx", x, parent.frame())
     on.exit(rm(xx, envir = parent.frame()))
     y
     get("xx") + 1
}

## This is fine:
> f(1, 2) 
[1] 2

## This is not:
> f(1, f(1, 2))
Error in get("xx") : object 'xx' not found

If you play these games whether you get the result you want, or an
obvious error, or just the wrong answer depends on argument evaluation
order and the like. You really don't want to go there. Not to mention
that you would be telling users they are not allowed to use '.' as a
variable name for their own purposes or you would be polluting their
environment with some other artificial symbol that they would see in
debugging. Just don't.

Anything going in base needs to worry even about artificial cases.
Yes, there are things in base that don't meet that standard. No, that
is not a reason to add more.

> I agree that restraining the pipe to a single placeholder (to avoid
> double evaluation) would be a good design too.
>
> I can't access https://gitlab.com/luke-tierney/pipes, it appears to be 404.

Should be able to get there now. Needed to change the visibility ---
still learning my way around gitlab.

Best,

luke

> Best,
> Lionel
>
>

-- 
Luke Tierney
Ralph E. Wareham Professor of Mathematical Sciences
University of Iowa                  Phone:             319-335-3386
Department of Statistics and        Fax:               319-335-3017
    Actuarial Science
241 Schaeffer Hall                  email:   luke-tierney using uiowa.edu
Iowa City, IA 52242                 WWW:  http://www.stat.uiowa.edu



More information about the R-devel mailing list