library(tidyverse)

Why pipe

You can use the pipe to rewrite multiple operations that you can read left-to-right, top-to-bottom (reading the pipe operator as “then”).

  • too many variables:

    n1 <- rnorm(10000)
    n2 <- abs(n1)
    n3 <- matrix(n2, ncol = 100)
    n4 <- rowMeans(n3)
    n5 <- round(n4)
    hist(n5)
  • nested functions:

    hist(round(rowMeans(matrix(abs(rnorm(10000)), ncol = 100))))
  • more readable with %>%!

    rnorm(10000) %>% 
      abs %>% 
      matrix(ncol = 50) %>% 
      rowMeans() %>% 
      round %>% 
      hist

Pipe make your code more readable by:

  • structuring sequences of data operations left-to-right (as opposed to from the inside and out),
  • avoiding nested function calls,
  • minimizing the need for local variables and function definitions, and
  • making it easy to add steps anywhere in the sequence of operations.

Usage

Basic piping

  • x %>% f is equivalent to f(x)
  • x %>% f(y) is equivalent to f(x, y)
  • x %>% f %>% g %>% h is equivalent to h(g(f(x)))

The argument placeholder

  • x %>% f(y, .) is equivalent to f(y, x)
  • x %>% f(y, z = .) is equivalent to f(y, z = x)

Re-using the placeholder for attributes

  • x %>% f(y = nrow(.), z = ncol(.)) is equivalent to f(x, y = nrow(x), z = ncol(x))

  • x %>% {f(y = nrow(.), z = ncol(.))} is equivalent to f(y = nrow(x), z = ncol(x))

Examples

instancename <- c('Cycle 1 Day 1', 'Cycle 2 Day 1')

folder <- instancename %>% 
  str_replace_all('Cycle (\\d+) Day (\\d+)', 'C\\1D\\2')

folder
## [1] "C1D1" "C2D1"
starwars %>% 
  select(name, height, species) %>% 
  filter(species %in% c('Human', 'Droid')) %>% 
  mutate(mean_height = mean(height, na.rm = T)) %>% 
  group_by(species) %>% 
  mutate(mean_height_by_species = mean(height, na.rm = T)) %>% 
  ungroup()
## # A tibble: 41 x 5
##    name               height species mean_height mean_height_by_species
##    <chr>               <int> <chr>         <dbl>                  <dbl>
##  1 Luke Skywalker        172 Human          170.                   177.
##  2 C-3PO                 167 Droid          170.                   131.
##  3 R2-D2                  96 Droid          170.                   131.
##  4 Darth Vader           202 Human          170.                   177.
##  5 Leia Organa           150 Human          170.                   177.
##  6 Owen Lars             178 Human          170.                   177.
##  7 Beru Whitesun lars    165 Human          170.                   177.
##  8 R5-D4                  97 Droid          170.                   131.
##  9 Biggs Darklighter     183 Human          170.                   177.
## 10 Obi-Wan Kenobi        182 Human          170.                   177.
## # … with 31 more rows