class: title-slide <br> <br> .right-panel[ # The Pipe Operator ## Dr. Mine Dogucu ] --- class: inverse middle .font50[Three solutions to a single problem] --- class: middle What is the average of 4, 8, 16 approximately? --- class: middle 1.What is the average of **4, 8, 16** approximately? --- class: middle 2.What is the **average** of 4, 8, 16 approximately? --- class: middle 3.What is the average of 4, 8, 16 **approximately**? --- class: middle inverse .font50[Solution 1: Functions within Functions] --- ```r c(4, 8, 16) ``` ``` ## [1] 4 8 16 ``` -- <hr> ```r mean(c(4, 8, 16)) ``` ``` ## [1] 9.333333 ``` -- <hr> ```r round(mean(c(4, 8, 16))) ``` ``` ## [1] 9 ``` --- class: middle **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. --- class: middle inverse .font50[Solution 2: Creating Objects] --- class: middle ```r numbers <- c(4, 8, 16) numbers ``` ``` ## [1] 4 8 16 ``` -- <hr> ```r avg_number <- mean(numbers) avg_number ``` ``` ## [1] 9.333333 ``` -- <hr> ```r round(avg_number) ``` ``` ## [1] 9 ``` --- class: middle **Problem with creating many objects** We will end up with too many objects in `Environment`. --- class: middle inverse .font50[Solution 3: The (forward) Pipe Operator %>% ] --- class: middle .font75[Shortcut: <br>Ctrl (Command) + Shift + M] --- class: middle .pull-left[ ```r c(4, 8, 16) %>% mean() %>% round() ``` ``` ## [1] 9 ``` ] .pull-right[ Combine 4, 8, and 16 `and then` Take the mean `and then` Round the output ] --- .pull-left[ ```r c(4, 8, 16) %>% mean() %>% round() ``` ] .pull-right[
] --- class: middle The output of the first function is the first argument of the second function. --- Do you recall composite functions such as `\(f \circ g(x)\)`? -- Now we have `\(f \circ g \circ h (x)\)` or `round(mean(c(4, 8, 16)))` -- .pull-left[ ```r h(x) %>% g() %>% f() ``` ] .pull-right[ ```r c(4, 8, 16) %>% mean() %>% round() ``` ]