liveBook · Manning

Recode() function

As explained in Statistics Slam Dunk

The car recode() function replaces values in a vector according to specified recoding rules.

The car recode() function replaces values in a vector according to named rules. It is especially useful when raw categories need clearer labels before analysis or visualization. section 2.3.5 section 15.3.2

Use recode() to:

  • Copy a variable, then collapse several position codes into broader basketball roles such as Big, Forward, Guard, and Swingman. section 2.3.5
  • Rename factor levels after reshaping games and wins into a single games variable, changing them to Played and Won. section 15.3.2
  • Convert the recoded character result to a factor when later analysis groups observations by its levels. section 2.3.5

Recoding NBA positions

Copy the original position variable, replace each code with a readable label, and convert the result to a factor: draft$Pos2 <- draft$Pos; draft$Pos2 <- recode(draft$Pos2, "C" = "Center", "C-F" = "Big", "F" = "Forward", "F-C" = "Big", "F-G" = "Swingman", "G" = "Guard", "G-F" = "Swingman"); draft$Pos2 <- as.factor(draft$Pos2). The resulting levels are Big, Center, Forward, Guard, and Swingman. section 2.3.5

draft$Pos2 <- draft$Pos
draft$Pos2 <- recode(draft$Pos2, 
                    "C" = "Center", 
                    "C-F" = "Big", 
                    "F" = "Forward", 
                    "F-C" = "Big", 
                    "F-G" = "Swingman", 
                    "G" = "Guard", 
                    "G-F" = "Swingman") 
draft$Pos <- as.factor(draft$Pos)
draft$Pos2 <- as.factor(draft$Pos2)
levels(draft$Pos2)
## [1] "Big"      "Center"   "Forward"  "Guard"    "Swingman"

Executable position-recoding code shows how several original categories can map to shared analytical labels. section 2.3.5

How Statistics Slam Dunk covers it

How deep it goes
Demonstrates named replacements, category consolidation, factor conversion, and relabeling after reshaping.
Examples
Uses NBA birthplace, college attendance, player positions, and franchise games-versus-wins labels.
What it assumes
Assumes familiarity with vectors, factors, assignment, and equality comparisons; demonstrates factor conversion alongside recoding.
What you can do after
Apply it via the car package to create readable or consolidated categorical values for analysis.
How it connects
Connects categorical variables with factors, mutate(), pivot_longer(), rename(), and grouped visualization.

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.