September 22, 2016

Pipes

Pipes

An easier way to read functions

  • We can put functions inside of functions
    • Math: \(f(g(x))\)
    • R: as.data.frame(read.csv("file.csv"))
  • Or we can think of the output of one function as the input of another
    • Math: \(y = g(x)\) then \(f(y)\)
    • R: read.csv("file.csv") %>% as.data.frame()
  • Using dplyr we can pipe the output of one function into another using %>%.

Pipes

An easier way to read functions

From Hadley Wickham:

x %>% f(y)
# is the same as:
f(x,y)

gapminder %>%
  group_by(continent, country) %>%
  nest()
# Same as:
nest(group_by(gapminder,continent,country))

Why should we do this?

Your code is how you communicate with others (especially your future self).

If it doesn't make any difference to the computer, you might as well write your code in a way that makes it easier for you to think about it and find errors.