I recently have been playing with creating my own pipes, using the awesome pipe_with()
function in magittr
. I am looking to track the number of pipes in the current chain (so my pipe can behave differently depending on its position in a chain). I thought I had the answer with this example from the magrittr
github page:
# 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
The number on the left hand side is the pipe number. However, when I run the same chain again, the numbers don't restart at 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
This is presumably because the local environment created by the first use of %L>%
is not destroyed when the last %L>%
in the chain is executed. So in order to tell the position of a pipe in the current chain (and not just since the first pipe in a session), there needs to be a way to set the count variable back to 0 when a chain ends (or to reset the local environment).
Does anyone have any ideas on how to do this?
In the current dev
branch, we are working with a new approach, due to the compound operator, %<>%
, where the last pipe has to know that it is last. Anyway, the implication is that a pipe relatively quickly has knowledge about this through a local value toplevel
which is either TRUE or FALSE. I don't know whether this is of any use.
In particular because pipe_with
is "on hold" due to the very limited interest received in it. It is therefore not a part of the current dev
branch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With