2016

Do you…

Some code examples…

Let's have a code:

x <- round(
    sum(
        colSums(
            t(
                matrix(data = rnorm(50), ncol = 5, nrow = 10)
                )
            ),
        na.rm = TRUE),
    digits = 3)

…and x is of course equal to 0.206.

Some code examples…

Hmm, what about writing it nicely:

x <- rnorm(50)
x <- matrix(data = x, ncol = 5, nrow = 10)
x <- t(x)
x <- colSums(x)
x <- sum(x, na.rm = TRUE)
x <- round(x, digits = 3)

We have a picture now, but it is still quite verbose.

Some nice code examples…

Are you ready for a plumbing job?

rnorm(50) %>% 
  matrix(data = ., ncol = 5, nrow = 10) %>% 
  t() %>% 
  colSums() %>% 
  sum(na.rm = TRUE) %>% 
  round(digits = 3) -> x

A concept of the pipe %>%

(Almost) every function has inputs (arguments) and outputs (values).

Pipe %>% channels output of a function to input of another function.

rnorm(50) %>% 
  matrix(data = ., ncol = 5, nrow = 10) %>% 
  t() %>% 
  colSums() %>% 
  sum(na.rm = TRUE) %>% 
  round(digits = 3) -> x

Using pipes (1)

By default an object runnig through a pipe is fed to the first argument of the right-hand side function.

If you want to fed another argument (or you want to be explicit) you need to use "placehoder" . to determine the destination of the pipe. You can use . more then once.

Using pipes (2)

We will demonstrate use of the placeholder with a function multiply():

multiply <- function(x = 1, y = -1) x*y
multiply()
## [1] -1

Using pipes (3)

# No placeholder
5 %>% multiply()
## [1] -5
# One placeholder
5 %>% multiply(y = .)
## [1] 5
# More placeholders
5 %>% multiply(x = ., y = .)
## [1] 25

Where can I get it?

Pipe is not implemented in base R.

It is part of packages dplyr and magrittr. dplyr contains only basic pipe (%>%). magrittr allows user to use more advanced options.

Where have I seen it before? Of course you know the pipe from:

  • Sherlock Holmes, and
  • your Unix/Linux shell (|).

(Sherlock Holmes is a fictional detective with a funny hat.)

Pipes and aliases of magrittr

library(magrittr)

magrittr provides extra three pipes (their descriptions are from vignette).

We will focus on %>% and %<>%.

Pipes: compound assignment

Compound assignment pipe operator %<>% (aka Moebius pipe) can be used as the first pipe in a chain. The effect will be that the result of the pipeline is assigned to the left-hand side object, rather than returning the result as usual.

x %>% sqrt -> x

is equivalent to

x %<>% sqrt

It is not necessary to write functions with (). x %<>% sqrt() is the same as x %<>% sqrt.

Aliases

When chaining functions you might need to use some pretty basic operations. It is impossible with bare +, -, or /. One need a series of functions similar to user-defined function multiply() defined above. magrittr provides a lot of such functions.

See help or handout.

Go for your own pipelines…