liveBook · Manning

Ifelse() function

As explained in Statistics Slam Dunk

The ifelse() function in R returns values selected elementwise from two alternatives according to a logical condition.

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.

How Statistics Slam Dunk covers it

How deep it goes
Explains conditional transformation through several worked data-wrangling examples but does not discuss implementation internals.
Examples
Uses birthplace, college attendance, playoff status, and top-eight ranking to demonstrate conditional variable creation.
What it assumes
Assumes basic data frames and columns while teaching logical comparison, missing-value handling, and factor conversion through examples.
What you can do after
Apply it via base R and dplyr to build binary or categorical variables from existing columns.
How it connects
Connects ifelse() with dplyr, mutate(), logical operators, missing values, factors, ranking, and logistic regression data preparation.

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.