Marie-Hélène Burle
email  twitter @MHBurle  github prosoitos
August 24, 2018

Magrittr less used "piping" treasures

Table of Contents

In the previous workshop section, we used this code:

banding <-
    bird = paste0("bird", 1:50),
    sex = sample(c("F", "M"), 50, replace = T),
    population = sample(LETTERS[1:3], 50, replace = T),
    mass = rnorm(50, 43, 4) %>% round(1),
    tarsus = rnorm(50, 27, 1) %>% round(1),
    wing = rnorm(50, 112, 3) %>% round(0)
  ) %T>% 

And you might have wondered:

Wait: what is this weird looking pipe?

Everybody is now familiar with the main magrittr pipe (%>%) and it comes with most of the tidyverse packages. This is why, even though magrittr is not one of the core packages, you do not have to load it to use the pipe.

But magrittr has several other treasures (to use them, you will have to load the package).


%<>% pipes the left expression to the right, and then back to the left. Instead of an arrow going right (as the main pipe is), think of it as an arrow going from left to right and then back left.

Basically, it replaces the variable to the left, after having been transformed by the expression to the right.

This is extremely convenient, but also dangerous: each time you run such line of code, your variable changes. To rerun the script, you need to first rerun the code that created the initial variable with that name.

The code:

banding %<>% modify_if(is.factor, as.character)

is equivalent to:

banding <-
  banding %>%
  modify_if(is.factor, as.character)


%T% pipes the effect of the left expression to the right, but does not pipe the object itself (so the object is "free" to be used by another pipe). This is very useful when you want to produce to output from one object or produce a side effect (e.g. printing) without interrupting a pipeline. I like to think of the "T" as a branching which represents the 2 outputs produced by a single object.

Try replacing %T% with the regular pipe %>% in our code at the top of this page.
What happens?
Can you explain it?

magrittr has other pipes and you should explore them at your own time!