logo

How to Use Pipe Operator %>% in R 📂R

How to Use Pipe Operator %>% in R

Overview

In R, the %>% is known as the Pipe Operator, and like all other operators, it performs a binary operation. The pipe operator, true to its name, allows values to travel through the pipeline, navigating through functions and enabling seamless data manipulation. To truly understand its utility, consider the following example.

Example

20190805\_163044.png

The example above calculates the square root of numbers from $1$ to $10$, takes the logarithm of those values, and then finds the median. This calculation may seem arbitrary and not particularly challenging to code, but if such expressions are frequently used, code readability can greatly diminish.

R is so convenient for data handling that even a rough piece of code can produce the intended results, meaning that no coder wants to waste memory. Consequently, this leads to the unconscious writing of codes with numerous nested parentheses. However, using pipes enables natural, conversational-like coding.

20190805\_162550.png Consider, for example, the trick of converting factors to numeric; with pipes, it’s possible to structure code in a way that mirrors human thought processes. The screenshot above is straightforward, but the readability of pipes becomes increasingly clear as the complexity of handling x in real data analysis grows.

Code

median(log(sqrt(1:10)))
1:10 %>% sqrt %>% log %>% median
 
x <- factor(c("3", "1", "2", "2", "1", "1", "5")); x
y1 <- as.numeric(as.character(x)); y1
y2 <- x %>% as.character%>% as.numeric; y2