# Pipes with magrittr

## Prerequisites

The %>% comes fromt he magrittr package by Stefan Milton Bache. It is included in tidyverse. But if we wanted to focuse entirely on %>%, we can load magrittr explicitly.

library(magrittr)

## Piping Alternatives

### Intermediate steps

The simplest approach is to save each step as a new object. But the downside is that it forces you to name each intermediate element. This leads to cluttered code and the need to increment the suffix on each line

Object_size gives the memory occupied by all of its arguments. The results show that since the two objects have similar columns, they wont be copied over.

library(tidyverse)
library(dplyr)
library(pryr)
diamonds <- ggplot2::diamonds
diamonds2 <-  diamonds %>%
mutate(pricepercarat = price / carat)
object_size(diamonds)
3.46 MB
object_size(diamonds2)
3.89 MB
object_size(diamonds2, diamonds)
3.89 MB

When you modify one of them, then that variable can no longer be shared between the two data frames and a copy must be made. The size of each data frame is unchanged, but the collecti size increases:

diamonds$carat[1] <- NA object_size(diamonds) 3.46 MB object_size(diamonds2) 3.89 MB object_size(diamonds2, diamonds) 4.32 MB ### Overwrite the original Instead of creating intermediat eobjects at each stpe, we could overwrite the original object. This is less typing and less mistakes, however, debugging is painful. The repetition of the object being transformed obscures what’s chagneing on each line. ### Function composition Just string the functions calls together. The disadvantage is that you have to read from inside out. From right to left and that the arguments end up spread far apart. The dagwood sandwich problem. ### Use the pipe The pipe works by performing a lexical transformation behind the scenes. Magrittr reassembes the code in the pipe to a form that works by overwriting an intermediate object. Pipe won’t work for two classes of functions: ### functions that use the current environment For example, assign() will create a new variable with the given name in the current enivronment: assign("x",10) x [1] 10 "x" %>% assign(100) x [1] 10 The use of assign with the pipe does not work because it assigns it to a temporary environment used by %>%. If you do want to use assign with the pipe, you must be explicit about the environment: env <- environment() "x" %>% assign(100, envir = env) x [1] 100 Other functions include: get() and load(). ### Functions that use lazy evaluation In R function arguments are only computed when the function uses them, not prior to calling the function. The pipe computes each element in turn, so you can’t rely on this behavior. One place that this is a problem is tryCatch() which lets you capture and handle errors. tryCatch(stop("!"), error = function(e) "An error") [1] "An error" stop("!") %>% tryCatch(error = function(e) "An error") Error in eval(expr, envir, enclos) : ! There are relatively wide class of functions with this behavior, including try(), suppressMessages(), and suppressWarnngs() in base R ## When Not to use Pipe Your pipes are longer than 10 steps You have mulitple inputs or outputs. You are thinking about a directed graph with a complex dependency structure. Pipes are fundamentally linear and expressing complex relationships with pipes will yield confusing codes ## Other Magrittr functions T pipe. Works like %>% but returns the left hand side results. rnorm(100) %>% matrix(ncol = 2) %>% plot()%>% str()  NULL rnorm(100) %>% matrix(ncol = 2) %T>% plot()%>% str()  num [1:50, 1:2] 0.3168 -0.1113 -1.6274 -0.0535 0.6482 ... If you are working with functions that don’t have a data frame based API (ie. you pass them individual vectors, not a data frame and expressions to be evaluate din the context of that data frame) you might find the %$% useful. It explodes out the variables in a data frame so that you can refer to them explicitly. This is useful when working with many functions in base R:

library(magrittr)

Attaching package: <U+393C><U+3E31>magrittr<U+393C><U+3E32>

The following object is masked from <U+393C><U+3E31>package:purrr<U+393C><U+3E32>:

set_names

The following object is masked from <U+393C><U+3E31>package:tidyr<U+393C><U+3E32>:

extract
mtcars %\$%
cor(disp, mpg)
[1] -0.8475514

For assignment magrittr provides the %<>% operator which allows you to replace code like this:

mtcars <-  mtcars %>%
transform(cyl = cyl *2)
mtcars

with this:

mtcars %<>% transform(cyl = cyl *2)
mtcars