liveBook · Manning

Mutate() function

As explained in Statistics Slam Dunk

The mutate() function from dplyr creates or modifies columns in a tabular data structure using expressions evaluated against existing columns.

mutate() from dplyr adds derived variables to a data set. Give each new column a name and an expression based on existing columns, then keep working with the expanded result. It is especially useful when a sports question needs a cleaner category, a numeric measure, or an analysis-ready outcome. section 2.3.5 section 11.4.1

A common workflow pipes a data frame into mutate() and assigns the result back to the same object. Expressions can use logical tests, arithmetic, string extraction, counts, or grouped calculations. Convert a resulting column to a factor or numeric class afterward when the next analysis requires it. section 2.3.5 section 8.4 section 12.3

mutate(draft, Born2 = ifelse(Born == "us", "USA", "World")) -> draft
draft$Born2 <- as.factor(draft$Born2)

This creates Born2 from Born: United States birth records become "USA" and all others become "World," then the result is made a factor. section 2.3.5

Use mutate() to derive columns for practical analytical jobs:

Build a field-goal percentage column

After tabulating made shots and misses by possession length, derive fg_pct as shot / (shot + miss) * 100. The new column turns two event counts into a percentage that can be plotted across seconds of a possession. section 8.5.1

mutate() supports later modeling and visualization by putting the needed measure directly beside the original data. For example, derive an opponent-points variable before studying team performance, a month index before analyzing a season schedule, or a free-throw percentage before drawing a streak chart. section 14.2.4 section 17.3 section 16.4.2

How Statistics Slam Dunk covers it

How deep it goes
Demonstrates worked expressions with conditionals, strings, arithmetic, grouping, and validation, without describing dplyr internals.
Examples
Uses birth country, college attendance, possession seconds, salaries, playoff status, field-goal percentage, and z-scores.
What it assumes
Introduces logical tests and distinguishes assignment from equality while using base R helpers alongside dplyr.
What you can do after
Apply it via dplyr to create conditional, numeric, grouped, and string-derived columns for analysis.
How it connects
Connects to dplyr pipelines, ifelse(), case_when(), group_by(), rank(), stringr, factors, and data standardization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.