2.9 The pipe operator
In practice we often have to call functions in a sequence. Suppose for example you have a vector of numbers. Of those numbers you would like to first compute the absolute value. Then you would like to compute the logarithm of those absolute values. Last you would like to compute the mean of those numbers. In standard R we can write this as
<- -5:-1
x mean(log(abs(x)))
## [1] 0.9574983
Such nested code where we apply multiple functions over the same line of code becomes cluttered and difficult to read.
For this reason the package magrittr
introduces the so-called pipe operator %>%
which makes the above code much more readable. Consider the same example using the pipe operator.
library(magrittr)
<- -5:-1
x %>% abs() %>% log() %>% mean() x
## [1] 0.9574983
The above code can be seen as follows: consider the vector x
and apply the function abs
over its entries. Then apply the function log
over the resulting vector and last apply the function mean
.
The code is equivalent to standard R but it is simpler to read. So sometimes it is preferrable to code using pipes instead of standard R syntax.