How to chain several operations together in R?

We can chain several operations in R by using the pipe operator (%>%) provided by the tidyverse collection. Using this operator allows creating a pipeline of functions where the output of the first function is passed as the input into the second function and so on, until the pipeline ends. This eliminates the need for creating additional variables and significantly enhances the overall code readability.

An example of using the pipe operator on a data frame:

df <- data.frame(a=1:4, b=11:14, c=21:24)
print(df)
​
df_new <- df %>% select(a, b) %>% filter(a > 2)
print(df_new)Powered By 

Output:

 a  b  c
1 1 11 21
2 2 12 22
3 3 13 23
4 4 14 24
  a  b
1 3 12
2 4 13

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *