Use ifelse() to create a derived variable by testing each record and choosing one value when the condition is true and another when it is false. With dplyr's mutate(), it turns messy NBA data into analysis-ready categories. section 2.3.5
A typical workflow is:
- Write the logical test with ==, not =; = assigns a value, whereas == compares values. section 2.3.5
- Pass the data to mutate() and assign the ifelse() result to a new variable. section 2.3.5
- Convert binary results to factors when later analysis groups observations by their levels. section 2.3.5
- Handle missing values before testing them; is.na() can replace missing College values with 0. section 2.3.5
Classifying players by birthplace
mutate(draft, Born2 = ifelse(Born == "us", "USA", "World")) -> draft draft$Born2 <- as.factor(draft$Born2) This creates Born2 as USA for records whose Born value is us and World for every other record, then stores the result as a factor. The same pattern creates College2: after missing College values are replaced with 0, ifelse(College == 0, 0, 1) distinguishes players without a listed college from those with one. section 2.3.5
Marking playoff teams and top teams
nba_stats %>% mutate(playoffs2 = ifelse(playoffs == 0, 0, 1)) -> nba_stats Here, playoffs2 converts the original playoff levels 0, 10, and 11 into a binary outcome: 0 remains 0, while every nonzero value becomes 1. A similar rule creates topTeam with ifelse(rank > 8, 0, 1), separating teams ranked outside the top eight from the rest.
