Skip to main content

Section 2.4 Meet the tidyverse

Last chapter, R was introduced. In this chapter, we will be building on the basic language and syntax we learned and build upon it with tidyverse.

Subsection 2.4.1 The Pipe

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:
Piping is telling R the sequence you want things to be done in code, and uses |>. Below is an example of how you would write something.
# 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:
  1. 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.
  2. The second reads left to right. It goes string |> function |> function. It takes the string, trims the whitespace, then turns it to uppercase.
The first starts with a function, the second starts with what we want the function(s) to be applied to.

When piping, the rule of thumb is:.

Each line in a pipeline should perform one clear transformation.