Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you tell if a pipe operator is the last (or first) in a chain?

Tags:

r

piping

magrittr

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?

like image 985
ecologician Avatar asked Jun 26 '14 01:06

ecologician


1 Answers

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.

like image 104
Stefan Avatar answered Sep 28 '22 16:09

Stefan