liveBook · Manning

Levels() function

As explained in Statistics Slam Dunk

The levels() function in R retrieves or sets the category labels associated with a factor.

Use R’s base levels() function to inspect the category labels stored in a factor. It helps reveal inconsistent labels before filtering, grouping, or recoding NBA data. section 8.4 section 2.3.5

Work through the function in three steps:

  • Convert a character variable with as.factor() when necessary; levels() returns NULL for an ordinary character string. section 8.4 section 2.3.5
  • Call levels(variable) to list every category currently represented by the factor. section 8.4
  • Read the output for spelling or formatting differences, then recode and call levels() again to verify the result. section 8.4 section 2.3.5

Finding inconsistent NBA game labels

After converting data_set to a factor, levels(pbp$data_set) reveals "2019-20 Regular Season" and "2019-2020 Regular Season" as separate categories, alongside "2019-20 Playoffs". That inspection supports filtering postseason plays before analysis.

Checking cleaned player positions

levels(as.factor(draft$Pos)) exposes raw labels such as C-F and F-C. After recoding Pos2 into categories such as Big and Swingman and converting it to a factor, levels(draft$Pos2) confirms the cleaned labels.

How Statistics Slam Dunk covers it

How deep it goes
Defines factor-only retrieval and demonstrates diagnostic and post-recoding checks, without covering broader factor manipulation.
Examples
Uses NBA dataset labels for seasons, event types, teams, and player positions to expose categories and verify cleanup.
What it assumes
Assumes basic R variables and data wrangling while teaching factor conversion with as.factor() when needed.
What you can do after
Evaluate/understand factor categories, identify inconsistent labels, and confirm that recoding produced the intended levels.
How it connects
Connects factors with as.factor(), character strings, recode(), filtering, and grouped counts.

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.