+ - 0:00:00
Notes for current slide
Notes for next slide



The Pipe Operator

Dr. Mine Dogucu

1 / 24

Three solutions to a single problem

2 / 24

What is the average of 4, 8, 16 approximately?

3 / 24

1.What is the average of 4, 8, 16 approximately?

4 / 24

2.What is the average of 4, 8, 16 approximately?

5 / 24

3.What is the average of 4, 8, 16 approximately?

6 / 24

Solution 1: Functions within Functions

7 / 24
c(4, 8, 16)
## [1] 4 8 16
8 / 24
c(4, 8, 16)
## [1] 4 8 16

mean(c(4, 8, 16))
## [1] 9.333333
9 / 24
c(4, 8, 16)
## [1] 4 8 16

mean(c(4, 8, 16))
## [1] 9.333333

round(mean(c(4, 8, 16)))
## [1] 9
10 / 24

Problem with writing functions within functions

Things will get messy and more difficult to read and debug as we deal with more complex operations on data.

11 / 24

Solution 2: Creating Objects

12 / 24
numbers <- c(4, 8, 16)
numbers
## [1] 4 8 16
13 / 24
numbers <- c(4, 8, 16)
numbers
## [1] 4 8 16

avg_number <- mean(numbers)
avg_number
## [1] 9.333333
14 / 24
numbers <- c(4, 8, 16)
numbers
## [1] 4 8 16

avg_number <- mean(numbers)
avg_number
## [1] 9.333333

round(avg_number)
## [1] 9
15 / 24

Problem with creating many objects

We will end up with too many objects in Environment.

16 / 24

Solution 3: The (forward) Pipe Operator %>%

17 / 24

Shortcut:
Ctrl (Command) + Shift + M

18 / 24
c(4, 8, 16) %>%
mean() %>%
round()
## [1] 9

Combine 4, 8, and 16 and then
Take the mean and then
Round the output

19 / 24
c(4, 8, 16) %>%
mean() %>%
round()

20 / 24

The output of the first function is the first argument of the second function.

21 / 24

Do you recall composite functions such as fg(x)?

22 / 24

Do you recall composite functions such as fg(x)?

Now we have fgh(x) or round(mean(c(4, 8, 16)))

23 / 24

Do you recall composite functions such as fg(x)?

Now we have fgh(x) or round(mean(c(4, 8, 16)))

h(x) %>%
g() %>%
f()
c(4, 8, 16) %>%
mean() %>%
round()
24 / 24

Three solutions to a single problem

2 / 24
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow