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:
- Create binary indicators with ifelse(), such as whether a player attended college or whether a team reached the playoffs. section 2.3.5 section 14.6.1
- Extract and convert values, such as the final seconds from a possession-length string or a four-digit season from a variable name. section 8.4 section 14.2.2
- Compute totals, averages, ratios, and standardized values from existing numeric columns. section 11.4.1 section 19.4.1
- Create values within groups, including duplicate flags, descending ranks, mean deviations, and scoring z-scores. section 12.3 section 12.4 section 18.4.4
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
