Here are three little functions that allow for brunching logical pipes as defined in magrittr
package. It is against Hadley’s idea, as pipes are in principle linear, and in general I agree, but sometimes it would be comfy to ramify pipes away. It overcomes native magrittr
%T>%
by allowing more than one step after cutting the pipe.
Imagine you need to create a list with means, correlations, and regression results. And you like to do it in one single pipe. In general, it is not possible, and you’ll have to start a second pipe, probably doing some redundant computations.
Here is an example that allows it:
data.frame(a=1:5, b=1/(1+exp(6:10)) ) %>% ramify(1) %>% branch(1) %>% colMeans %>% branch(2) %>% lm(a ~ b, .) %>% broom::tidy(.) %>% branch(3) %>% cor %>% ramify(2) %>% branch(1) %>% round(2) %>% branch(2) %>% psych::fisherz(.) %>% harvest(2) %>% harvest
ramify()
– Saves current result into temporary object.buf
and identifies a point in the pipe where branching will happen. Argument is an id of ramification.branch()
– Starts a new brunch from theramify
point. (brunch(1) can be omitted, as ramify creates the first brunch. Second argument is a family of branches, or parent branch. By default it uses the last parent branch created by last usedramify
.harvest()
– Returns contents of all the brunches as a list and clears the buffer.
See proof of concept https://gist.github.com/MaksimRudnev/bf81eab9f39bd830f9f167c669444472
“Pipes are fundamentally linear and expressing complex relationships with them will typically yield confusing code.”
http://r4ds.had.co.nz/pipes.html#when-not-to-use-the-pipe