::p_load(tidyverse) pacman
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
<- c(3, 5, 8)
a <- sqrt(a)
b <- mean(b)
c 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:
<- as_tibble(PlantGrowth)
tbl 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.
%>% lm(weight ~ group, data = .) tbl
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.