3.4 The Pipe Operator

The pipe operator %>% from the tidyverse package strings together a series of functions into a single command. It will take the output from the first function and use it as the input for the second, take the output from the second as input for the third, etc. For example, creating a sequence from 0 to 100 with intervals of 2, calculating the sum of these numbers, and calculating (and printing) the square root of this sum, can be done in three ways.

  a = seq(0,100,2) 
  b = sum(a)
  c = sqrt(b)
  c
## [1] 50.5
  sqrt(sum(seq(0,100,2)))
## [1] 50.5
  seq(0,100,2) %>%   # pipes the sequence forward   
    sum() %>%        # take the sum of the sequence; pipe forward 
    sqrt()           # square root
## [1] 50.5

The pipe operator becomes a very useful feature as you move to performing complex, multi-step operations. It allows carrying out a series of manipulations to an object without having to create a new named object each step of the way, or getting lost in endless nesting of parentheses within a command.