pacman::p_load(tidyverse)

About pipe

Here’s a mini example 1. Create a vector 2. Calculate the square root of this vector 3. Calculate the mean of the square root of the result 4. Calculate the square root of the result

Option 1: Nesting Functions

sqrt(mean(sqrt(c(3, 5, 8))))
[1] 1.505163
  • PRO: Not much code
  • CON: Hard to read

Option 2: Intermediate Results

  • PRO: Easy to read
  • CON: A lot of code, unnecessary intermediate results
a <- c(3, 5, 8)
b <- sqrt(a)
c <- mean(b)
sqrt(c)
[1] 1.505163

Option 3: Pipe Operator

These do the same thing:

sqrt(c(3, 5, 8))      # baseR
[1] 1.732051 2.236068 2.828427
c(3, 5, 8) %>% sqrt() # Pipe
[1] 1.732051 2.236068 2.828427

Thus the final solution by using the pipe operator is:

c(3, 5, 8) %>% sqrt() %>% mean() %>% sqrt()
[1] 1.505163

Deal with functions with additional arguments

What if I want to pipe my object into an argument of a function that is NOT the first argument? For example:

tbl <- as_tibble(PlantGrowth)
lm(weight ~ group, data = tbl)

Call:
lm(formula = weight ~ group, data = tbl)

Coefficients:
(Intercept)    grouptrt1    grouptrt2  
      5.032       -0.371        0.494  

Answer: Use a dot to say which argument to pipe to.

tbl %>% lm(weight ~ group, data = .)

Call:
lm(formula = weight ~ group, data = .)

Coefficients:
(Intercept)    grouptrt1    grouptrt2  
      5.032       -0.371        0.494  

But what about this Operator: |>

There’s minor difference but %>% operator is still bettern than |> operator. Find more information from this tutorial.