I would like to make a custom magrittr pipe that is essentially the same as %>%
, but has some extra functionality added to it, as a side effect. E.g. print some information, tabulate or plot the intermediate results or update a progress bar.
Looking around if something like this exists, I found the tee pipe %T>%
that can be used to add a statement in the pipeline itself (“inline” so to speak). I also found this answer that specifies %V%
, to do nothing with the inputs and just pass it along, to add some inline side effect that is unrelated to the pipe contents.
Neither of these is what I am looking for. I want a custom function to specify a pipe that can replace a %>%
(or a |>
) without change of pipe functionality.
I wonder if this can be done easily.
3
%>%
is a function in magrittr, so it’s possible to look at the source code and modify it to add extra functionality. For example to define a function that prints the head of the first argument:
library(magrittr)
library(dplyr)
#Define a new function based on `%>%`
`%P%` <- function (lhs, rhs)
{
print(head(lhs)) #Add in some extra functionality
lhs <- substitute(lhs)
rhs <- substitute(rhs)
kind <- 1L
env <- parent.frame()
lazy <- TRUE
.External2(magrittr:::magrittr_pipe)
}
iris %P% group_by(Species) %P% summarise(Petal.Width = mean(Petal.Width))
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
# # A tibble: 6 × 5
# # Groups: Species [1]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# <dbl> <dbl> <dbl> <dbl> <fct>
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
# # A tibble: 3 × 2
# Species Petal.Width
# <fct> <dbl>
# 1 setosa 0.246
# 2 versicolor 1.33
# 3 virginica 2.03
Note that the source code for the pipe can be found with
`%>%`
2