knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "README-"
)

mmpipe

Install with devtools::install_gh("moodymudskipper/mmpipe")

This package proposes new pipe operators, a function to define custom operators easily, 2 other pipe friendly functions for conditional steps or printing.

magrittr's operators are also exported so they can be used without attaching alias functions.

new operators

When we attach mmpipe the functions magrittr:::is_pipe and magrittr:::wrap_function are modified to register our new pipes in the package, thus a couple warnings are displayed.

library(mmpipe)

silence a warning:

data.frame(a = c(1,-1)) %W>% transform(a = sqrt(a))

log steps in the console:

iris %L>% {Sys.sleep(1);head(.,2)} %L>% {Sys.sleep(2);.[4:5]}

use print, summary or glimpse on output:

iris %P>% head(2) %P>% `[`(4:5)

iris %S>% head(2) %S>% `[`(4:5)

iris %G>% head(2) %G>% `[`(4:5)

view steps of chain in the viewer:

iris %V>% head(2) %V>% `[`(4:5)

debug the chain:

iris %>% head(2) %D>% `[`(4:5)

time operations:

iris %C>% head(2) %C>% {Sys.sleep(2);.} 

Create your own pipe operators with add_pipe

We create an operator by feeding to add_pipe its raw name and the modified body of the expression a regular pipe call would return.

the operator is created and magrittr's namespace is modified to make the new operator compatible.

This is not obvious so let's see some examples, if we wanted to recreate existing operators.

Redefining %P2>% as %P>% twin :

 add_pipe(`%P2>%`, substitute({. <- print(b);cat("\n"); .}, list(b = body)))
 iris %P2>% head(3) %>% head(2)

Redefining %T2>% as %T>% twin :

 add_pipe(`%T2>%`, call("{", body, quote(.)))
 iris %T2>% {message("side effect")} %>% head(2)

Redefining %W2>% as %W>% twin :

 add_pipe(`%W2>%`, substitute(
     {options(warn = -1); on.exit(options(warn = w)); b},
     list(w = options()$warn, b = body)))
 data.frame(a = c(1,-1)) %W2>% transform(a = sqrt(a))

See magrittr:::wrap_function's code for a better understanding.

See also functions rm_pipe and list_pipes.

easy conditional steps with pif

Using functions:

iris %>% pif(is.data.frame, dim, nrow)

Using formulas:

iris %>% pif(~is.numeric(Species), ~"numeric :)",~paste(class(Species)[1],":("))

Using raw expressions:

iris %>% pif(nrow(iris) > 2, head(iris,2))

Be careful with expressions!

iris %>% pif(TRUE, dim,  warning("this will be evaluated"))
iris %>% pif(TRUE, dim, ~warning("this won't be evaluated"))

print info on intermediate steps with pprint

library(ggplot2)
iris %>%
  pprint(~"hello")           %>%
  head(2)                    %>%
  transform(Species = NULL)  %>%
  pprint(rowSums,na.rm = TRUE) %>%
  pprint(~setNames(.[1:2],toupper(names(.[1:2])))) %>%
  pprint(dim)


moodymudskipper/mmpipe documentation built on May 17, 2019, 10:39 a.m.