Applied Metaphors: Learning TRIZ, Complexity, Data/Stats/ML using Metaphors
  1. Introduction to the dplyr package
  • Teaching
    • Data Analytics for Managers and Creators
      • Tools
        • Introduction to R and RStudio
        • Introduction to Radiant
        • Introduction to Orange
      • Descriptive Analytics
        • Data
        • Summaries
        • Counts
        • Quantities
        • Groups
        • Densities
        • Groups and Densities
        • Change
        • Proportions
        • Parts of a Whole
        • Evolution and Flow
        • Ratings and Rankings
        • Surveys
        • Time
        • Space
        • Networks
        • Experiments
        • Miscellaneous Graphing Tools, and References
      • Statistical Inference
        • 🧭 Basics of Statistical Inference
        • 🎲 Samples, Populations, Statistics and Inference
        • Basics of Randomization Tests
        • 🃏 Inference for a Single Mean
        • 🃏 Inference for Two Independent Means
        • 🃏 Inference for Comparing Two Paired Means
        • Comparing Multiple Means with ANOVA
        • Inference for Correlation
        • 🃏 Testing a Single Proportion
        • 🃏 Inference Test for Two Proportions
      • Inferential Modelling
        • Modelling with Linear Regression
        • Modelling with Logistic Regression
        • 🕔 Modelling and Predicting Time Series
      • Predictive Modelling
        • 🐉 Intro to Orange
        • ML - Regression
        • ML - Classification
        • ML - Clustering
      • Prescriptive Modelling
        • 📐 Intro to Linear Programming
        • 💭 The Simplex Method - Intuitively
        • 📅 The Simplex Method - In Excel
      • Workflow
        • Facing the Abyss
        • I Publish, therefore I Am
      • Case Studies
        • Demo:Product Packaging and Elderly People
        • Ikea Furniture
        • Movie Profits
        • Gender at the Work Place
        • Heptathlon
        • School Scores
        • Children's Games
        • Valentine’s Day Spending
        • Women Live Longer?
        • Hearing Loss in Children
        • California Transit Payments
        • Seaweed Nutrients
        • Coffee Flavours
        • Legionnaire’s Disease in the USA
        • Antarctic Sea ice
        • William Farr's Observations on Cholera in London
    • R for Artists and Managers
      • 🕶 Lab-1: Science, Human Experience, Experiments, and Data
      • Lab-2: Down the R-abbit Hole…
      • Lab-3: Drink Me!
      • Lab-4: I say what I mean and I mean what I say
      • Lab-5: Twas brillig, and the slithy toves…
      • Lab-6: These Roses have been Painted !!
      • Lab-7: The Lobster Quadrille
      • Lab-8: Did you ever see such a thing as a drawing of a muchness?
      • Lab-9: If you please sir…which way to the Secret Garden?
      • Lab-10: An Invitation from the Queen…to play Croquet
      • Lab-11: The Queen of Hearts, She Made some Tarts
      • Lab-12: Time is a Him!!
      • Iteration: Learning to purrr
      • Lab-13: Old Tortoise Taught Us
      • Lab-14: You’re are Nothing but a Pack of Cards!!
    • ML for Artists and Managers
      • 🐉 Intro to Orange
      • ML - Regression
      • ML - Classification
      • ML - Clustering
      • 🕔 Modelling Time Series
    • TRIZ for Problem Solvers
      • I am Water
      • I am What I yam
      • Birds of Different Feathers
      • I Connect therefore I am
      • I Think, Therefore I am
      • The Art of Parallel Thinking
      • A Year of Metaphoric Thinking
      • TRIZ - Problems and Contradictions
      • TRIZ - The Unreasonable Effectiveness of Available Resources
      • TRIZ - The Ideal Final Result
      • TRIZ - A Contradictory Language
      • TRIZ - The Contradiction Matrix Workflow
      • TRIZ - The Laws of Evolution
      • TRIZ - Substance Field Analysis, and ARIZ
    • Math Models for Creative Coders
      • Maths Basics
        • Vectors
        • Matrix Algebra Whirlwind Tour
        • content/courses/MathModelsDesign/Modules/05-Maths/70-MultiDimensionGeometry/index.qmd
      • Tech
        • Tools and Installation
        • Adding Libraries to p5.js
        • Using Constructor Objects in p5.js
      • Geometry
        • Circles
        • Complex Numbers
        • Fractals
        • Affine Transformation Fractals
        • L-Systems
        • Kolams and Lusona
      • Media
        • Fourier Series
        • Additive Sound Synthesis
        • Making Noise Predictably
        • The Karplus-Strong Guitar Algorithm
      • AI
        • Working with Neural Nets
        • The Perceptron
        • The Multilayer Perceptron
        • MLPs and Backpropagation
        • Gradient Descent
      • Projects
        • Projects
    • Data Science with No Code
      • Data
      • Orange
      • Summaries
      • Counts
      • Quantity
      • 🕶 Happy Data are all Alike
      • Groups
      • Change
      • Rhythm
      • Proportions
      • Flow
      • Structure
      • Ranking
      • Space
      • Time
      • Networks
      • Surveys
      • Experiments
    • Tech for Creative Education
      • 🧭 Using Idyll
      • 🧭 Using Apparatus
      • 🧭 Using g9.js
    • Literary Jukebox: In Short, the World
      • Italy - Dino Buzzati
      • France - Guy de Maupassant
      • Japan - Hisaye Yamamoto
      • Peru - Ventura Garcia Calderon
      • Russia - Maxim Gorky
      • Egypt - Alifa Rifaat
      • Brazil - Clarice Lispector
      • England - V S Pritchett
      • Russia - Ivan Bunin
      • Czechia - Milan Kundera
      • Sweden - Lars Gustaffsson
      • Canada - John Cheever
      • Ireland - William Trevor
      • USA - Raymond Carver
      • Italy - Primo Levi
      • India - Ruth Prawer Jhabvala
      • USA - Carson McCullers
      • Zimbabwe - Petina Gappah
      • India - Bharati Mukherjee
      • USA - Lucia Berlin
      • USA - Grace Paley
      • England - Angela Carter
      • USA - Kurt Vonnegut
      • Spain-Merce Rodoreda
      • Israel - Ruth Calderon
      • Israel - Etgar Keret
  • Posts
  • Blogs and Talks

On this page

  • Introduction
  • Setting up the Packages
  • Tidy Data
  • Data: starwars
  • Single table verbs
    • The pipe
    • Filter rows with filter()
    • Arrange rows with arrange()
    • Choose rows using their position with slice()
    • Select columns with select()
    • Add new columns with mutate()
    • Change column order with relocate()
    • Summarise values with summarise()
    • Commonalities
  • Combining functions with %>%
  • Patterns of operations
    • Selecting operations
    • Mutating operations
  • Two table verbs

Introduction to the dplyr package

Author

Arvind Venkatadri

Published

July 6, 2021

Modified

December 12, 2024

Introduction

One of the dominant paradigms of working with data in R is to render it into “tidy” form. A huge benefit of the tidy way of working is that it influences your thinking with data and helps plan out your operations, in going from purpose to actual code in a swift and intuitive manner. This tidy form allows for a huge variety of data manipulation, summarizing, and plotting tasks, that can be performed using the packages of the tidyverse, and other packages that leverage the power of the tidyverse.

Setting up the Packages

knitr::opts_chunk$set(message = TRUE) # Want tidylog messages
library(tidyverse)
library(tidylog) ## Explains what happens with dplyr verbs

Tidy Data

data(starwars)
dim(starwars)
[1] 87 14
starwars
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
Luke Skywalker17277.0blondfairblue19.0male
C-3PO16775.0NAgoldyellow112.0none
R2-D29632.0NAwhite, bluered33.0none
Darth Vader202136.0nonewhiteyellow41.9male
Leia Organa15049.0brownlightbrown19.0female
Owen Lars178120.0brown, greylightblue52.0male
Beru Whitesun Lars16575.0brownlightblue47.0female
R5-D49732.0NAwhite, redredNAnone
Biggs Darklighter18384.0blacklightbrown24.0male
Obi-Wan Kenobi18277.0auburn, whitefairblue-gray57.0male
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 14 columns

“Tidy Data” is an important way of thinking about what data typically look like in R. Let’s fetch a figure from the web to show the (preferred) structure of data in R.

Tidy Data

Tidy Data

The three features described in the figure above define the nature of tidy data:

  • Variables in Columns
  • Observations in Rows and
  • Measurements in Cells.

Data are imagined to be resulting from an experiment. Each variable represents a parameter/aspect in the experiment. Each row represents an additional datum of measurement. A cell is a single measurement on a single parameter(column) in a single observation(row).

When working with data you must:

  • Figure out what you want to do. (Purpose)
  • Describe those tasks in the form of a computer program. (Plain English to R Code)
  • Execute the program.

The dplyr package makes these steps fast and easy:

  • By constraining your options, it helps you think about your data manipulation challenges.
  • It provides simple “verbs”, functions that correspond to the most common data manipulation tasks, to help you translate your thoughts into code.
  • It uses efficient backends, so you spend less time waiting for the computer.

Ne’er you mind about backends ;-) See Shakespeare’s Hamlet.

This document introduces you to dplyr’s basic set of tools, and shows you how to apply them to data frames. dplyr also supports databases via the dbplyr package, once you’ve installed, read vignette("dbplyr") to learn more.

Data: starwars

To explore the basic data manipulation verbs of dplyr, we’ll use the dataset starwars. This dataset contains 87 characters and comes from the Star Wars API, and is documented in ?starwars

This means: type ?starwars in the Console. Try.

Note that starwars is a tibble, a modern re-imagining of the data frame. It’s particularly useful for large datasets because it only prints the first few rows. You can learn more about tibbles at https://tibble.tidyverse.org; in particular you can convert data frames to tibbles with as_tibble().

Check your Environment Tab to inspect starwars in a separate tab.

Single table verbs

dplyr aims to provide a function for each basic verb of data manipulation. These verbs can be organised into three categories based on the component of the dataset that they work with:

  • Rows:
    • filter() chooses rows based on column values.
    • slice() chooses rows based on location.
    • arrange() changes the order of the rows.
  • Columns:
    • select() changes whether or not a column is included.
    • rename() changes the name of columns.
    • mutate() changes the values of columns and creates new columns.
    • relocate() changes the order of the columns.
  • Groups of rows:
    • summarise() collapses a group into a single row.

Think of the parallels from Microsoft Excel.

The pipe

All of the dplyr functions take a data frame (or tibble) as the first argument. Rather than forcing the user to either save intermediate objects or nest functions, dplyr provides the %>% operator from magrittr. x %>% f(y) turns into f(x, y) so the result from one step is then “piped” into the next step. You can use the pipe to rewrite multiple operations that you can read left-to-right, top-to-bottom (reading the pipe operator as “then”).

Filter rows with filter()

filter() allows you to select a subset of rows in a data frame. Like all single verbs, the first argument is the tibble (or data frame). The second and subsequent arguments refer to variables within that data frame, selecting rows where the expression is TRUE.

For example, we can select all character with light skin color and brown eyes with:

Note the double equal to sign (==) below! Equivalent to MS Excel Data -> Filter

starwars %>% filter(skin_color == "light", eye_color == "brown")
filter: removed 80 rows (92%), 7 rows remaining
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
gender
<chr>
homeworld
<chr>
Leia Organa15049brownlightbrown19femalefeminineAlderaan
Biggs Darklighter18384blacklightbrown24malemasculineTatooine
Padmé Amidala18545brownlightbrown46femalefeminineNaboo
Cordé157NAbrownlightbrownNANANANaboo
Dormé165NAbrownlightbrownNAfemalefeminineNaboo
Raymus Antilles18879brownlightbrownNAmalemasculineAlderaan
Poe DameronNANAbrownlightbrownNAmalemasculineNA
7 rows | 1-10 of 14 columns

Arrange rows with arrange()

arrange() works similarly to filter() except that instead of filtering or selecting rows, it reorders them. It takes a data frame, and a set of column names (or more complicated expressions) to order by. If you provide more than one column name, each additional column will be used to break ties in the values of preceding columns:

starwars %>% arrange(height, mass)
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
Yoda6617.0whitegreenbrown896.0male
Ratts Tyerel7915.0nonegrey, blueunknownNAmale
Wicket Systri Warrick8820.0brownbrownbrown8.0male
Dud Bolt9445.0noneblue, greyyellowNAmale
R2-D29632.0NAwhite, bluered33.0none
R4-P1796NAnonesilver, redred, blueNAnone
R5-D49732.0NAwhite, redredNAnone
Sebulba11240.0nonegrey, redorangeNAmale
Gasgano122NAnonewhite, blueblackNAmale
Watto137NAblackblue, greyyellowNAmale
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 14 columns

Use desc() to order a column in descending order:

starwars %>% arrange(desc(height))
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
Yarael Poof264NAnonewhiteyellowNAmale
Tarfful234136.0brownbrownblueNAmale
Lama Su22988.0nonegreyblackNAmale
Chewbacca228112.0brownunknownblue200.0male
Roos Tarpals22482.0nonegreyorangeNAmale
Grievous216159.0nonebrown, whitegreen, yellowNAmale
Taun We213NAnonegreyblackNAfemale
Rugor Nass206NAnonegreenorangeNAmale
Tion Medon20680.0nonegreyblackNAmale
Darth Vader202136.0nonewhiteyellow41.9male
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 14 columns

Choose rows using their position with slice()

slice() lets you index rows by their (integer) locations. It allows you to select, remove, and duplicate rows.

This is an important step in Prediction, Modelling and Machine Learning.

We can get characters from row numbers 5 through 10.

starwars %>% slice(5:10)
slice: removed 81 rows (93%), 6 rows remaining
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
gender
<chr>
homeworld
<chr>
Leia Organa15049brownlightbrown19femalefeminineAlderaan
Owen Lars178120brown, greylightblue52malemasculineTatooine
Beru Whitesun Lars16575brownlightblue47femalefeminineTatooine
R5-D49732NAwhite, redredNAnonemasculineTatooine
Biggs Darklighter18384blacklightbrown24malemasculineTatooine
Obi-Wan Kenobi18277auburn, whitefairblue-gray57malemasculineStewjon
6 rows | 1-10 of 14 columns

It is accompanied by a number of helpers for common use cases:

  • slice_head() and slice_tail() select the first or last rows.
starwars %>% slice_head(n = 3)
slice_head: removed 84 rows (97%), 3 rows remaining
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
gender
<chr>
homeworld
<chr>
Luke Skywalker17277blondfairblue19malemasculineTatooine
C-3PO16775NAgoldyellow112nonemasculineTatooine
R2-D29632NAwhite, bluered33nonemasculineNaboo
3 rows | 1-10 of 14 columns
  • slice_sample() randomly selects rows. Use the option prop to choose a certain proportion of the cases.
starwars %>% slice_sample(n = 5)
slice_sample: removed 82 rows (94%), 5 rows remaining
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
gender
<chr>
homeworld
<chr>
Chewbacca228112brownunknownblue200malemasculineKashyyyk
Mace Windu18884nonedarkbrown72malemasculineHaruun Kal
R2-D29632NAwhite, bluered33nonemasculineNaboo
BB8NANAnonenoneblackNAnonemasculineNA
Yarael Poof264NAnonewhiteyellowNAmalemasculineQuermia
5 rows | 1-10 of 14 columns
starwars %>% slice_sample(prop = 0.1)
slice_sample: removed 79 rows (91%), 8 rows remaining
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
gender
<chr>
homeworld
<chr>
Watto137NAblackblue, greyyellowNAmalemasculineToydaria
Saesee Tiin188NAnonepaleorangeNAmalemasculineIktotch
Ratts Tyerel7915nonegrey, blueunknownNAmalemasculineAleen Minor
Leia Organa15049brownlightbrown19.0femalefeminineAlderaan
Owen Lars178120brown, greylightblue52.0malemasculineTatooine
Arvel CrynydNANAbrownfairbrownNAmalemasculineNA
Lobot17579nonelightblue37.0malemasculineBespin
Anakin Skywalker18884blondfairblue41.9malemasculineTatooine
8 rows | 1-10 of 14 columns

Use replace = TRUE to perform a bootstrap sample. If needed, you can weight the sample with the weight argument.

Bootstrap samples are a special statistical sampling method. Counterintuitive perhaps, since you sample with replacement. Should remind you of your high school Permutation and Combination class, with all those urn models and so on. If you remember.

  • slice_min() and slice_max() select rows with highest or lowest values of a variable. Note that we first must choose only the values which are not NA.
starwars %>%
  filter(!is.na(height)) %>%
  slice_min(height, n = 3)
filter: removed 6 rows (7%), 81 rows remaining
slice_min: removed 78 rows (96%), 3 rows remaining
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
gender
<chr>
homeworld
<chr>
Yoda6617whitegreenbrown896malemasculineNA
Ratts Tyerel7915nonegrey, blueunknownNAmalemasculineAleen Minor
Wicket Systri Warrick8820brownbrownbrown8malemasculineEndor
3 rows | 1-10 of 14 columns

Select columns with select()

Often you work with large datasets with many columns but only a few are actually of interest to you. select() allows you to rapidly zoom in on a useful subset using operations that usually only work on numeric variable positions:

# Select columns by name
starwars %>% select(hair_color, skin_color, eye_color)
select: dropped 11 variables (name, height, mass, birth_year, sex, …)
ABCDEFGHIJ0123456789
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
blondfairblue
NAgoldyellow
NAwhite, bluered
nonewhiteyellow
brownlightbrown
brown, greylightblue
brownlightblue
NAwhite, redred
blacklightbrown
auburn, whitefairblue-gray
Next
123456
...
9
Previous
1-10 of 87 rows
# Select all columns between hair_color and eye_color (inclusive)
starwars %>% select(hair_color:eye_color)
select: dropped 11 variables (name, height, mass, birth_year, sex, …)
ABCDEFGHIJ0123456789
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
blondfairblue
NAgoldyellow
NAwhite, bluered
nonewhiteyellow
brownlightbrown
brown, greylightblue
brownlightblue
NAwhite, redred
blacklightbrown
auburn, whitefairblue-gray
Next
123456
...
9
Previous
1-10 of 87 rows
# Select all columns except those from hair_color to eye_color (inclusive)
starwars %>% select(!(hair_color:eye_color))
select: dropped 3 variables (hair_color, skin_color, eye_color)
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
birth_year
<dbl>
sex
<chr>
gender
<chr>
homeworld
<chr>
species
<chr>
films
<list>
Luke Skywalker17277.019.0malemasculineTatooineHuman<chr [5]>
C-3PO16775.0112.0nonemasculineTatooineDroid<chr [6]>
R2-D29632.033.0nonemasculineNabooDroid<chr [7]>
Darth Vader202136.041.9malemasculineTatooineHuman<chr [4]>
Leia Organa15049.019.0femalefeminineAlderaanHuman<chr [5]>
Owen Lars178120.052.0malemasculineTatooineHuman<chr [3]>
Beru Whitesun Lars16575.047.0femalefeminineTatooineHuman<chr [3]>
R5-D49732.0NAnonemasculineTatooineDroid<chr [1]>
Biggs Darklighter18384.024.0malemasculineTatooineHuman<chr [1]>
Obi-Wan Kenobi18277.057.0malemasculineStewjonHuman<chr [6]>
Next
123456
...
9
Previous
1-10 of 87 rows | 1-9 of 11 columns
# Select all columns ending with color
starwars %>% select(ends_with("color"))
select: dropped 11 variables (name, height, mass, birth_year, sex, …)
ABCDEFGHIJ0123456789
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
blondfairblue
NAgoldyellow
NAwhite, bluered
nonewhiteyellow
brownlightbrown
brown, greylightblue
brownlightblue
NAwhite, redred
blacklightbrown
auburn, whitefairblue-gray
Next
123456
...
9
Previous
1-10 of 87 rows

There are a number of helper functions you can use within select(), like starts_with(), ends_with(), matches() and contains(). These let you quickly match larger blocks of variables that meet some criterion. See ?select for more details.

You can rename variables with select() by using named arguments:

starwars %>% select(home_world = homeworld)
select: renamed one variable (home_world) and dropped 13 variables
ABCDEFGHIJ0123456789
home_world
<chr>
Tatooine
Tatooine
Naboo
Tatooine
Alderaan
Tatooine
Tatooine
Tatooine
Tatooine
Stewjon
Next
123456
...
9
Previous
1-10 of 87 rows

But because select() drops all the variables not explicitly mentioned, it’s not that useful. Instead, use rename():

starwars %>% rename(home_world = homeworld)
rename: renamed one variable (home_world)
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
Luke Skywalker17277.0blondfairblue19.0male
C-3PO16775.0NAgoldyellow112.0none
R2-D29632.0NAwhite, bluered33.0none
Darth Vader202136.0nonewhiteyellow41.9male
Leia Organa15049.0brownlightbrown19.0female
Owen Lars178120.0brown, greylightblue52.0male
Beru Whitesun Lars16575.0brownlightblue47.0female
R5-D49732.0NAwhite, redredNAnone
Biggs Darklighter18384.0blacklightbrown24.0male
Obi-Wan Kenobi18277.0auburn, whitefairblue-gray57.0male
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 14 columns

Add new columns with mutate()

Besides selecting sets of existing columns, it’s often useful to add new columns that are functions of existing columns. This is the job of mutate():

starwars %>% mutate(height_m = height / 100)
mutate: new variable 'height_m' (double) with 46 unique values and 7% NA
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
Luke Skywalker17277.0blondfairblue19.0male
C-3PO16775.0NAgoldyellow112.0none
R2-D29632.0NAwhite, bluered33.0none
Darth Vader202136.0nonewhiteyellow41.9male
Leia Organa15049.0brownlightbrown19.0female
Owen Lars178120.0brown, greylightblue52.0male
Beru Whitesun Lars16575.0brownlightblue47.0female
R5-D49732.0NAwhite, redredNAnone
Biggs Darklighter18384.0blacklightbrown24.0male
Obi-Wan Kenobi18277.0auburn, whitefairblue-gray57.0male
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 15 columns

We can’t see the height in meters we just calculated, but we can fix that using a select command.

starwars %>%
  mutate(height_m = height / 100) %>%
  select(height_m, height, everything())
mutate: new variable 'height_m' (double) with 46 unique values and 7% NA
select: columns reordered (height_m, height, name, mass, hair_color, …)
ABCDEFGHIJ0123456789
height_m
<dbl>
height
<int>
name
<chr>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
1.72172Luke Skywalker77.0blondfairblue19.0
1.67167C-3PO75.0NAgoldyellow112.0
0.9696R2-D232.0NAwhite, bluered33.0
2.02202Darth Vader136.0nonewhiteyellow41.9
1.50150Leia Organa49.0brownlightbrown19.0
1.78178Owen Lars120.0brown, greylightblue52.0
1.65165Beru Whitesun Lars75.0brownlightblue47.0
0.9797R5-D432.0NAwhite, redredNA
1.83183Biggs Darklighter84.0blacklightbrown24.0
1.82182Obi-Wan Kenobi77.0auburn, whitefairblue-gray57.0
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 15 columns

dplyr::mutate() is similar to the base transform(), but allows you to refer to columns that you’ve just created:

starwars %>%
  mutate(
    height_m = height / 100,
    BMI = mass / (height_m^2)
  ) %>%
  select(BMI, everything())
mutate: new variable 'height_m' (double) with 46 unique values and 7% NA
        new variable 'BMI' (double) with 59 unique values and 32% NA
select: columns reordered (BMI, name, height, mass, hair_color, …)
ABCDEFGHIJ0123456789
BMI
<dbl>
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
26.02758Luke Skywalker17277.0blondfairblue19.0
26.89232C-3PO16775.0NAgoldyellow112.0
34.72222R2-D29632.0NAwhite, bluered33.0
33.33007Darth Vader202136.0nonewhiteyellow41.9
21.77778Leia Organa15049.0brownlightbrown19.0
37.87401Owen Lars178120.0brown, greylightblue52.0
27.54821Beru Whitesun Lars16575.0brownlightblue47.0
34.00999R5-D49732.0NAwhite, redredNA
25.08286Biggs Darklighter18384.0blacklightbrown24.0
23.24598Obi-Wan Kenobi18277.0auburn, whitefairblue-gray57.0
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 16 columns

If you only want to keep the new variables, use transmute():

starwars %>%
  transmute(
    height_m = height / 100,
    BMI = mass / (height_m^2)
  )
transmute: dropped 14 variables (name, height, mass, hair_color, skin_color, …)
transmute: dropped 14 variables (name, height, mass, hair_color, skin_color, …)
           new variable 'height_m' (double) with 46 unique values and 7% NA
           new variable 'BMI' (double) with 59 unique values and 32% NA
ABCDEFGHIJ0123456789
height_m
<dbl>
BMI
<dbl>
1.7226.02758
1.6726.89232
0.9634.72222
2.0233.33007
1.5021.77778
1.7837.87401
1.6527.54821
0.9734.00999
1.8325.08286
1.8223.24598
Next
123456
...
9
Previous
1-10 of 87 rows

Change column order with relocate()

Use a similar syntax as select() to move blocks of columns at once

starwars %>% relocate(sex:homeworld, .before = height)
relocate: columns reordered (name, sex, gender, homeworld, height, …)
ABCDEFGHIJ0123456789
name
<chr>
sex
<chr>
gender
<chr>
homeworld
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
Luke SkywalkermalemasculineTatooine17277.0blondfair
C-3POnonemasculineTatooine16775.0NAgold
R2-D2nonemasculineNaboo9632.0NAwhite, blue
Darth VadermalemasculineTatooine202136.0nonewhite
Leia OrganafemalefeminineAlderaan15049.0brownlight
Owen LarsmalemasculineTatooine178120.0brown, greylight
Beru Whitesun LarsfemalefeminineTatooine16575.0brownlight
R5-D4nonemasculineTatooine9732.0NAwhite, red
Biggs DarklightermalemasculineTatooine18384.0blacklight
Obi-Wan KenobimalemasculineStewjon18277.0auburn, whitefair
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 14 columns

Summarise values with summarise()

The last verb is summarise(). It collapses a data frame to a single row.

starwars %>% summarise(mean_height = mean(height, na.rm = TRUE))
summarise: now one row and one column, ungrouped
ABCDEFGHIJ0123456789
mean_height
<dbl>
174.6049
1 row

It’s not that useful until we learn the group_by() verb below.

Commonalities

You may have noticed that the syntax and function of all these verbs are very similar:

  • The first argument is a data frame.

  • The subsequent arguments describe what to do with the data frame. You can refer to columns in the data frame directly without using $.

  • The result is a new data frame

Together these properties make it easy to chain together multiple simple steps to achieve a complex result.

These five functions provide the basis of a language of data manipulation. At the most basic level, you can only alter a tidy data frame in five useful ways: you can reorder the rows (arrange()), pick observations and variables of interest (filter() and select()), add new variables that are functions of existing variables (mutate()), or collapse many values to a summary (summarise()).

Combining functions with %>%

The dplyr API is functional in the sense that function calls don’t have side-effects. You must always save their results. This doesn’t lead to particularly elegant code, especially if you want to do many operations at once. You either have to do it step-by-step:

a1 <- group_by(starwars, species, sex)
a2 <- select(a1, height, mass)
a3 <- summarise(a2,
  height = mean(height, na.rm = TRUE),
  mass = mean(mass, na.rm = TRUE)
)

Or if you don’t want to name the intermediate results, you need to wrap the function calls inside each other:

summarise(
  select(
    group_by(starwars, species, sex),
    height, mass
  ),
  height = mean(height, na.rm = TRUE),
  mass = mean(mass, na.rm = TRUE)
)
group_by: 2 grouping variables (species, sex)
Adding missing grouping variables: `species`, `sex`
select: dropped 10 variables (name, hair_color, skin_color, eye_color, birth_year, …)
summarise: now 41 rows and 4 columns, one group variable remaining (species)
ABCDEFGHIJ0123456789
species
<chr>
sex
<chr>
height
<dbl>
mass
<dbl>
Aleenamale79.000015.00000
Besaliskmale198.0000102.00000
Cereanmale198.000082.00000
Chagrianmale196.0000NaN
Clawditefemale168.000055.00000
Droidnone131.200069.75000
Dugmale112.000040.00000
Ewokmale88.000020.00000
Geonosianmale183.000080.00000
Gunganmale208.666774.00000
Next
12345
Previous
1-10 of 41 rows

This is difficult to read because the order of the operations is from inside to out. Thus, the arguments are a long way away from the function. To get around this problem, dplyr provides the %>% operator from magrittr. x %>% f(y) turns into f(x, y) so you can use it to rewrite multiple operations that you can read left-to-right, top-to-bottom (reading the pipe operator as “then”):

starwars %>%
  group_by(species, sex) %>%
  summarise(
    mean_height = mean(height, na.rm = TRUE),
    mean_mass = mean(mass, na.rm = TRUE)
  )
group_by: 2 grouping variables (species, sex)
summarise: now 41 rows and 4 columns, one group variable remaining (species)
ABCDEFGHIJ0123456789
species
<chr>
sex
<chr>
mean_height
<dbl>
mean_mass
<dbl>
Aleenamale79.000015.00000
Besaliskmale198.0000102.00000
Cereanmale198.000082.00000
Chagrianmale196.0000NaN
Clawditefemale168.000055.00000
Droidnone131.200069.75000
Dugmale112.000040.00000
Ewokmale88.000020.00000
Geonosianmale183.000080.00000
Gunganmale208.666774.00000
Next
12345
Previous
1-10 of 41 rows

Patterns of operations

The dplyr verbs can be classified by the type of operations they accomplish (we sometimes speak of their semantics, i.e., their meaning). It’s helpful to have a good grasp of the difference between select and mutate operations.

Selecting operations

One of the appealing features of dplyr is that you can refer to columns from the tibble as if they were regular variables. However, the syntactic uniformity of referring to bare column names hides semantical differences across the verbs. A column symbol supplied to select() does not have the same meaning as the same symbol supplied to mutate().

Selecting operations expect column names and positions. Hence, when you call select() with bare variable names, they actually represent their own positions in the tibble. The following calls are completely equivalent from dplyr’s point of view:

# `name` represents the integer 1
select(starwars, name)
select: dropped 13 variables (height, mass, hair_color, skin_color, eye_color,
…)
ABCDEFGHIJ0123456789
name
<chr>
Luke Skywalker
C-3PO
R2-D2
Darth Vader
Leia Organa
Owen Lars
Beru Whitesun Lars
R5-D4
Biggs Darklighter
Obi-Wan Kenobi
Next
123456
...
9
Previous
1-10 of 87 rows
select(starwars, 1)
select: dropped 13 variables (height, mass, hair_color, skin_color, eye_color,
…)
ABCDEFGHIJ0123456789
name
<chr>
Luke Skywalker
C-3PO
R2-D2
Darth Vader
Leia Organa
Owen Lars
Beru Whitesun Lars
R5-D4
Biggs Darklighter
Obi-Wan Kenobi
Next
123456
...
9
Previous
1-10 of 87 rows

By the same token, this means that you cannot refer to variables from the surrounding context if they have the same name as one of the columns. In the following example, height still represents 2, not 5:

height <- 5
select(starwars, height)
select: dropped 13 variables (name, mass, hair_color, skin_color, eye_color, …)
ABCDEFGHIJ0123456789
height
<int>
172
167
96
202
150
178
165
97
183
182
Next
123456
...
9
Previous
1-10 of 87 rows

One useful subtlety is that this only applies to bare names and to selecting calls like c(height, mass) or height:mass. In all other cases, the columns of the data frame are not put in scope. This allows you to refer to contextual variables in selection helpers:

name <- "color"
select(starwars, ends_with(name))
select: dropped 11 variables (name, height, mass, birth_year, sex, …)
ABCDEFGHIJ0123456789
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
blondfairblue
NAgoldyellow
NAwhite, bluered
nonewhiteyellow
brownlightbrown
brown, greylightblue
brownlightblue
NAwhite, redred
blacklightbrown
auburn, whitefairblue-gray
Next
123456
...
9
Previous
1-10 of 87 rows

These semantics are usually intuitive. But note the subtle difference:

name <- 5
select(starwars, name, identity(name))
select: dropped 12 variables (height, mass, hair_color, eye_color, birth_year,
…)
ABCDEFGHIJ0123456789
name
<chr>
skin_color
<chr>
Luke Skywalkerfair
C-3POgold
R2-D2white, blue
Darth Vaderwhite
Leia Organalight
Owen Larslight
Beru Whitesun Larslight
R5-D4white, red
Biggs Darklighterlight
Obi-Wan Kenobifair
Next
123456
...
9
Previous
1-10 of 87 rows

In the first argument, name represents its own position 1. In the second argument, name is evaluated in the surrounding context and represents the fifth column.

Mutating operations

Mutate semantics are quite different from selection semantics. Whereas select() expects column names or positions, mutate() expects column vectors. We will set up a smaller tibble to use for our examples.

df <- starwars %>% select(name, height, mass)
select: dropped 11 variables (hair_color, skin_color, eye_color, birth_year,
sex, …)

When we use select(), the bare column names stand for their own positions in the tibble. For mutate() on the other hand, column symbols represent the actual column vectors stored in the tibble. Consider what happens if we give a string or a number to mutate():

mutate(df, "height", 2)
mutate: new variable '"height"' (character) with one unique value and 0% NA
        new variable '2' (double) with one unique value and 0% NA
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
"height"
<chr>
2
<dbl>
Luke Skywalker17277.0height2
C-3PO16775.0height2
R2-D29632.0height2
Darth Vader202136.0height2
Leia Organa15049.0height2
Owen Lars178120.0height2
Beru Whitesun Lars16575.0height2
R5-D49732.0height2
Biggs Darklighter18384.0height2
Obi-Wan Kenobi18277.0height2
Next
123456
...
9
Previous
1-10 of 87 rows

mutate() gets length-1 vectors that it interprets as new columns in the data frame. These vectors are recycled so they match the number of rows. That’s why it doesn’t make sense to supply expressions like "height" + 10 to mutate(). This amounts to adding 10 to a string! The correct expression is:

mutate(df, height + 10)
mutate: new variable 'height + 10' (double) with 46 unique values and 7% NA
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
height + 10
<dbl>
Luke Skywalker17277.0182
C-3PO16775.0177
R2-D29632.0106
Darth Vader202136.0212
Leia Organa15049.0160
Owen Lars178120.0188
Beru Whitesun Lars16575.0175
R5-D49732.0107
Biggs Darklighter18384.0193
Obi-Wan Kenobi18277.0192
Next
123456
...
9
Previous
1-10 of 87 rows

In the same way, you can unquote values from the context if these values represent a valid column. They must be either length 1 (they then get recycled) or have the same length as the number of rows. In the following example we create a new vector that we add to the data frame:

var <- seq(1, nrow(df))
mutate(df, new = var)
mutate: new variable 'new' (integer) with 87 unique values and 0% NA
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
new
<int>
Luke Skywalker17277.01
C-3PO16775.02
R2-D29632.03
Darth Vader202136.04
Leia Organa15049.05
Owen Lars178120.06
Beru Whitesun Lars16575.07
R5-D49732.08
Biggs Darklighter18384.09
Obi-Wan Kenobi18277.010
Next
123456
...
9
Previous
1-10 of 87 rows

A case in point is group_by(). While you might think it has select semantics, it actually has mutate semantics. This is quite handy as it allows to group by a modified column:

group_by(starwars, sex)
group_by: one grouping variable (sex)
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
Luke Skywalker17277.0blondfairblue19.0male
C-3PO16775.0NAgoldyellow112.0none
R2-D29632.0NAwhite, bluered33.0none
Darth Vader202136.0nonewhiteyellow41.9male
Leia Organa15049.0brownlightbrown19.0female
Owen Lars178120.0brown, greylightblue52.0male
Beru Whitesun Lars16575.0brownlightblue47.0female
R5-D49732.0NAwhite, redredNAnone
Biggs Darklighter18384.0blacklightbrown24.0male
Obi-Wan Kenobi18277.0auburn, whitefairblue-gray57.0male
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 14 columns
group_by(starwars, sex = as.factor(sex))
group_by: one grouping variable (sex)
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<fct>
Luke Skywalker17277.0blondfairblue19.0male
C-3PO16775.0NAgoldyellow112.0none
R2-D29632.0NAwhite, bluered33.0none
Darth Vader202136.0nonewhiteyellow41.9male
Leia Organa15049.0brownlightbrown19.0female
Owen Lars178120.0brown, greylightblue52.0male
Beru Whitesun Lars16575.0brownlightblue47.0female
R5-D49732.0NAwhite, redredNAnone
Biggs Darklighter18384.0blacklightbrown24.0male
Obi-Wan Kenobi18277.0auburn, whitefairblue-gray57.0male
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 14 columns
group_by(starwars, height_binned = cut(height, 3))
group_by: one grouping variable (height_binned)
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
hair_color
<chr>
skin_color
<chr>
eye_color
<chr>
birth_year
<dbl>
sex
<chr>
Luke Skywalker17277.0blondfairblue19.0male
C-3PO16775.0NAgoldyellow112.0none
R2-D29632.0NAwhite, bluered33.0none
Darth Vader202136.0nonewhiteyellow41.9male
Leia Organa15049.0brownlightbrown19.0female
Owen Lars178120.0brown, greylightblue52.0male
Beru Whitesun Lars16575.0brownlightblue47.0female
R5-D49732.0NAwhite, redredNAnone
Biggs Darklighter18384.0blacklightbrown24.0male
Obi-Wan Kenobi18277.0auburn, whitefairblue-gray57.0male
Next
123456
...
9
Previous
1-10 of 87 rows | 1-8 of 15 columns

This is why you can’t supply a column name to group_by(). This amounts to creating a new column containing the string recycled to the number of rows:

group_by(df, "month")
group_by: one grouping variable ("month")
ABCDEFGHIJ0123456789
name
<chr>
height
<int>
mass
<dbl>
"month"
<chr>
Luke Skywalker17277.0month
C-3PO16775.0month
R2-D29632.0month
Darth Vader202136.0month
Leia Organa15049.0month
Owen Lars178120.0month
Beru Whitesun Lars16575.0month
R5-D49732.0month
Biggs Darklighter18384.0month
Obi-Wan Kenobi18277.0month
Next
123456
...
9
Previous
1-10 of 87 rows

Two table verbs

Sometimes our data is spread across more than one table. Often these tables are linked by some common, or common-looking, variable columns. dplyr allows us to work with such data that is spread over more than one table. More information is available here: Two Table Verbs in dplyr

The operations/verbs used to manipulate two-table verbs are:

  • Mutating joins, which add new variables to one table from matching rows in another.
    • inner_join()

  • left_join()

  • right_join()

  • full_join()

  • Filtering joins, which filter observations from one table based on whether or not they match an observation in the other table.
    • semi_join(x, y) keeps all observations in x that have a match in y.

  • anti_join(x, y) drops all observations in x that have a match in

  • Set operations, which combine the observations in the data sets as if they were set elements.

    • union()

  • union_all(),

  • intersect(),

  • setdiff()

  • Tidyr Operations:
  • pivot_longer()
  • pivot_wider()

Back to top

License: CC BY-SA 2.0

Website made with ❤️ and Quarto, by Arvind V.

Hosted by Netlify .