One of the best things that the tidyverse has to offer is called piping. It technically comes from the magrittr package. What makes the tidyverse package so ubiquitous with R is that tidyverse is actually a collection of R packages in one package. By installing and loading the tidyverse package, you are actually installing and loading a bevy of packages and significantly powering up your R session. Here are the packages included in tidyverse:
# In base R, to find the square root of a number, we would use this:
sqrt(42)
# With piping, we could rewrite it like this:
42 |> sqrt()
[1] 6.480741
[1] 6.480741
The Native Pipe |> vs. %>%.
The native pipe |> is built into R and is the modern standard. However, you will often see older code using %>%. That version requires the magrittr or tidyverse package to be loaded to work.
In base R, code is written inside out. What I mean by that is that base R code is often evaluated from the inside out. You take the 42 (inside the square root) and then square root it. With piping, it is read left to right. First this, then this, etc.
Letβs use a more potent example. Youβre starting this book and have been thinking, βi love r!β. It is all lowercase and has whitespace before and after the words. However, you love R so much you want it to be in all caps, and you donβt want whitespace ruining your exclamation. Below is the way to do this in base R and then using piping.
For reference, the str_to_upper() command capitalizes everything in a string, and the str_trim() removes leading and trailing whitespace in a string. Both are a part of the stringr package in the tidyverse.
str_to_upper(str_trim(" i love r! "))
" i love r! " |> str_trim() |> str_to_upper()
# You can also move down instead if you like
# " Adelie " |>
# str_trim() |>
# str_to_upper()
[1] "I LOVE R!"
[1] "I LOVE R!"
Those two pieces of code do the same thing, but they look very different:
The first reads right to left, or middle to outer. It starts with the string inside the str_trim(), then you have to move outward to the str_to_upper(), moving right to left moving from parenthesis to parenthesis.