*Note that you can click the three-line (hamburger) icon on the bottom-left of the slides to access a navigation menu. You can click inside the slides region and press the left and right arrow keys on your keyboard to advance and reverse the slides and animations.
Practice
1) Combining and Extracting Text
Using the starwars dataset (included in {dplyr}), let’s generate descriptive text for each character.
First, use select() to keep just the name, species, and homeworld columns.
Use str_glue() inside a mutate() step to create a new column called description that dynamically inserts the character’s information into the string.
Create another column called home_abbr that uses str_sub() to extract only the first three letters of the character’s homeworld.
Answer key
library(tidyverse)data("starwars", package ="dplyr")starwars |>select(name, species, homeworld) |>mutate(description =str_glue("{name} is a {species} from {homeworld}."),home_abbr =str_sub(homeworld, start =1, end =3) )## # A tibble: 87 × 5## name species homeworld description home_abbr## <chr> <chr> <chr> <glue> <chr> ## 1 Luke Skywalker Human Tatooine Luke Skywalker is a Human fro… Tat ## 2 C-3PO Droid Tatooine C-3PO is a Droid from Tatooin… Tat ## 3 R2-D2 Droid Naboo R2-D2 is a Droid from Naboo. Nab ## 4 Darth Vader Human Tatooine Darth Vader is a Human from T… Tat ## 5 Leia Organa Human Alderaan Leia Organa is a Human from A… Ald ## 6 Owen Lars Human Tatooine Owen Lars is a Human from Tat… Tat ## 7 Beru Whitesun Lars Human Tatooine Beru Whitesun Lars is a Human… Tat ## 8 R5-D4 Droid Tatooine R5-D4 is a Droid from Tatooin… Tat ## 9 Biggs Darklighter Human Tatooine Biggs Darklighter is a Human … Tat ## 10 Obi-Wan Kenobi Human Stewjon Obi-Wan Kenobi is a Human fro… Ste ## # ℹ 77 more rows
2) Separating Product Codes
Data often comes with multiple pieces of information stored in a single column. Let’s practice splitting them apart using a simulated inventory dataset.
First, run the code provided below to create the inventory dataset.
Use separate_wider_delim() to split the item column into three separate columns: "furniture", "wood_type", and "price".
Let’s use regular expressions (regex) to find specific patterns in text and clean them up using building blocks like anchors and character classes.
Start with the starwars dataset and use filter() with str_detect() to find all characters whose name starts with either “A” or “S”. Hint: Use an anchor and a character class.
Use mutate() and str_remove_all() to create a new column called no_spaces that removes all whitespace from the names.
Select only the name and no_spaces columns to verify your work.
Answer key
starwars |>filter(str_detect(name, "^[AS]")) |>mutate(no_spaces =str_remove_all(name, "\\s") ) |>select(name, no_spaces)## # A tibble: 11 × 2## name no_spaces ## <chr> <chr> ## 1 Anakin Skywalker AnakinSkywalker## 2 Ackbar Ackbar ## 3 Arvel Crynyd ArvelCrynyd ## 4 Sebulba Sebulba ## 5 Shmi Skywalker ShmiSkywalker ## 6 Ayla Secura AylaSecura ## 7 Adi Gallia AdiGallia ## 8 Saesee Tiin SaeseeTiin ## 9 San Hill SanHill ## 10 Shaak Ti ShaakTi ## 11 Sly Moore SlyMoore
[12b] Factors
Topics
Understand the difference between character strings and factors
Control the order of categorical data in plots and tables
Recode, collapse, and “lump” factor levels to simplify messy data
*Note that you can click the three-line (hamburger) icon on the bottom-left of the slides to access a navigation menu. You can click inside the slides region and press the left and right arrow keys on your keyboard to advance and reverse the slides and animations.
Practice
1) Ordering Factors by Value
Using the mpg dataset (included in {ggplot2}), let’s create a bar chart that is ordered meaningfully instead of alphabetically.
First, calculate the average engine size (displ) for each manufacturer using summarize() and the .by argument. Name the new column mean_displ.
Use mutate() and fct_reorder() to reorder the manufacturer factor based on the calculated mean_displ.
Pipe the result into ggplot() and create a horizontal bar chart (geom_col()) with mean_displ on the x-axis and manufacturer on the y-axis.
Look at the plot to answer: which manufacturers make the largest and smallest engines on average?
*Note that you can click the three-line (hamburger) icon on the bottom-left of the slides to access a navigation menu. You can click inside the slides region and press the left and right arrow keys on your keyboard to advance and reverse the slides and animations.
Practice
1) Parsing Dates from Strings
Let’s convert human-readable text into proper machine-readable dates.
Run the code below to load a small dataset of historical events.
Use mutate() and the appropriate {lubridate} parsing function to convert the date_str column into a proper Date object. Name the new column actual_date.
presidents |>mutate(life_span =interval(start = born, end = died),age_years = life_span /years(1) )## # A tibble: 2 × 5## name born died life_span age_years## <chr> <date> <date> <Interval> <dbl>## 1 George Washing… 1732-02-22 1799-12-14 1732-02-22 UTC--1799-12-14 UTC 67.8## 2 Abraham Lincoln 1809-02-12 1865-04-15 1809-02-12 UTC--1865-04-15 UTC 56.2