Pipe %>% Operator in R

Pipe %>% Operator in R is used to sequence of multiple operations. Pipe operators, available in magrittr, dplyr, and other R packages. Aim of pipe is to increase the performance of operation.

Usage:

1. Load dplyr(or magrittr) package.

library(dplyr)

2. Example 1: perform mean on sequence numbers from 1 to 20.

> 1:20 %>% mean [1] 10.5

3. Print the 6 random number of mtcars dataset of column mpg is greater than 25 in descending order.

library(dplyr)
result < - mtcars %>% filter(mpg>25) %>% sample_n(size=6) %>% arrange(desc(mpg))
result

mpg cyl disp hp drat wt qsec vs am gear carb 1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 2 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 3 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 4 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 5 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 6 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2

Explanation: First filter gets information of mpg whose value is greater than 25 on mtcars dataset, then that value is store in memory. Now, sample_n gets random 6 values of mptcars. Then, arrange applied on 6 values to get the output in descending order.

The same results can be obtained in with following operations.
a< -filter(mtcars,mpg>20)
b< -sample_n(a,size=6) arrange(b,desc(mpg)) arrange(b,desc(mpg))

mpg cyl disp hp drat wt qsec vs am gear carb
1 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
2 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
3 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
4 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
5 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
6 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4

Conclusion: From above example, instead of running multiple steps(3), we can run multiple operations in single line using Pipe oeprator %>%.

Responses are currently closed, but you can trackback from your own site.

Comments are closed.

Powered by k2schools
%d bloggers like this: