最近,我一直在使用magittr中可怕的magittr函数来创建自己的管道。我希望跟踪当前链中的管道数量(因此,根据管道在链中的位置,我的管道的行为可以有所不同)。我想我已经从magrittr github页面得到了这个例子的答案:
# 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左手边的号码是管道号码。但是,当我再次运行相同的链时,数字不会在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这大概是因为第一次使用%L>%创建的本地环境在执行链中的最后一个%L>%时不会被破坏。因此,为了告诉管道在当前链中的位置(而不仅仅是从会话中的第一个管道开始),需要有一种方法在链结束时将count变量设置为0(或者重置本地环境)。
有没有人对怎么做有任何想法?
发布于 2014-06-26 06:29:43
在当前的dev分支中,由于复合运算符%<>%,我们正在使用一种新的方法,其中最后一个管道必须知道它是最后一个。不管怎么说,这意味着管道通过一个本地值toplevel相对较快地了解到了这一点,这个值要么是真要么是假的。我不知道这是否有用。
特别是因为pipe_with由于收到的兴趣非常有限而被“搁置”。因此,它不是当前dev分支的一部分。
发布于 2014-06-26 02:25:47
实际上,只是想出了一种方法。只需计算子字符串"%L>“在match.call中出现的次数:
> lhs_trace2 <- function(x) {
+ cl <- match.call()
+ counter <- gregexpr("%L>%", cl[[2]], fixed = TRUE)[[1]]
+ if (counter[1] == -1) count <- 1 else count <- length(counter) + 1
+ cat(sprintf("%d: lhs = %s\n", count, deparse(cl[[2]])))
+ }
>
> # Then attach it to a new pipe
> `%L>%` <- pipe_with(lhs_trace2)
>
> # 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然后再运行一次:
> 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.8556344https://stackoverflow.com/questions/24421250
复制相似问题