# Good
fit_models.R
utility_functions.R
# Bad
fit models.R
foo.r
stuff.r
lab1.rIntroduction to tidyverse
1 The tidyverse Style Guide
canyoureadthissentence?
Good coding style is like correct punctuation: you can manage without it, but it makes things easier to read.
The most important thing about the tidyverse style guide is that it provides consistency, making code easier to write because you need to make fewer decisions.
2 The Pipe Operator
What is the average of 4, 8, 16 — approximately?
Breaking the problem down:
- What is the average of 4, 8, 16 approximately?
- What is the average of 4, 8, 16 approximately?
- What is the average of 4, 8, 16 approximately?
Code
c(4, 8, 16)[1] 4 8 16
Code
mean(c(4, 8, 16))[1] 9.333333
Code
round(mean(c(4, 8, 16)))[1] 9
Problem: Things get messy and harder to read as operations become more complex.
Code
numbers <- c(4, 8, 16)
numbers[1] 4 8 16
Code
avg_number <- mean(numbers)
avg_number[1] 9.333333
Code
round(avg_number)[1] 9
Problem: We end up with too many objects cluttering the Environment.
|>
First, load the tidyverse:
Code
# install.packages("tidyverse")
library(tidyverse)The pipe |> passes the output of one function as the first argument of the next.
Keyboard shortcut: Ctrl/Cmd + Shift + M
Code
c(4, 8, 16) |>
mean() |>
round()[1] 9
Read this as: Combine 4, 8, and 16, then take the mean, then round the result.
This is equivalent to the composite function \[f \circ g \circ h(x)\], or round(mean(c(4, 8, 16))) — but much easier to read.
Generalized form
h(x) |>
g() |>
f()Our example
Code
c(4, 8, 16) |>
mean() |>
round()3 Practice: The Pipe Operator
3.1 Exercise 1: Top 3 Scores
A class got these quiz scores: 72, 88, 95, 61, 79, 100, 83. Use the pipe to find the top 3 scores, from highest to lowest.
Hint: try sort(), rev(), and head().
Code
c(72, 88, 95, 61, 79, 100, 83) |>
sort() |>
rev() |>
head(3)[1] 100 95 88
3.2 Exercise 2: How Many Words?
Count the number of words in the sentence "To be or not to be that is the question".
Hint: try strsplit(), unlist(), and length().
Code
"To be or not to be that is the question" |>
strsplit(split = " ") |>
unlist() |>
length()[1] 10