如何判断管道操作员是否是链中的最后一个(或第一个)?

eco*_*ian 5 r piping magrittr

我最近一直在玩创建自己的管道,使用了很棒的pipe_with()功能magittr.我期待跟踪当前链中的管道数量(因此我的管道可以根据其在链中的位置而表现不同).我以为我从magrittrgithub页面得到了这个例子的答案:

# Create your own pipe with side-effects. In this example 
# we create a pipe with a "logging" function that traces
# the left-hand sides of a chain. First, the logger:
lhs_trace <- local({
  count <- 0
  function(x) {
    count <<- count + 1
    cl <- match.call()
    cat(sprintf("%d: lhs = %s\n", count, deparse(cl[[2]])))
  }
})

# Then attach it to a new pipe
`%L>%` <- pipe_with(lhs_trace)

# Try it out.
1:10 %L>% sin %L>% cos %L>% abs

1: lhs = 1:10
2: lhs = 1:10 %L>% sin
3: lhs = 1:10 %L>% sin %L>% cos
 [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009 0.9612168 0.7918362 0.5492263 0.9162743 0.8556344
Run Code Online (Sandbox Code Playgroud)

左侧的数字是管道编号.但是,当我再次运行相同的链时,数字不会在1处重新启动:

> 1:10 %L>% sin %L>% cos %L>% abs
4: lhs = 1:10
5: lhs = 1:10 %L>% sin
6: lhs = 1:10 %L>% sin %L>% cos
 [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009 0.9612168 0.7918362 0.5492263 0.9162743 0.8556344
Run Code Online (Sandbox Code Playgroud)

这可能是因为第一次使用时创建的本地环境在执行链中%L>%的最后一个时不会被破坏%L>%.因此,为了告诉当前链中管道的位置(而不仅仅是自会话中的第一个管道),需要有一种方法可以在链结束时将计数变量设置回0(或重置当地环境).

有没有人对如何做到这一点有任何想法?

Ste*_*fan 4

在当前dev分支中,我们正在使用一种新方法,由于复合运算符,%<>%其中最后一个管道必须知道它是最后一个。toplevel无论如何,这意味着管道可以相对快速地通过本地值(TRUE 或 FALSE)了解这一点。我不知道这个有没有用。

特别pipe_with是因为收到的利息非常有限而被“搁置”。因此它不是当前分支的一部分dev