2016
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.
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.
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
%>%
(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
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.
We will demonstrate use of the placeholder with a function multiply()
:
multiply <- function(x = 1, y = -1) x*y multiply()
## [1] -1
# No placeholder 5 %>% multiply()
## [1] -5
# One placeholder 5 %>% multiply(y = .)
## [1] 5
# More placeholders 5 %>% multiply(x = ., y = .)
## [1] 25
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 is a fictional detective with a funny hat.)
magrittr
library(magrittr)
magrittr
provides extra three pipes (their descriptions are from vignette).
We will focus on %>%
and %<>%
.
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 asx %<>% sqrt
.
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.