`as.factor()` converts a vector to a factor: an R variable with a set of categorical levels. Use it when values represent categories or ordered groups with a finite set of possible values, rather than measurements to analyze as numbers. Converting early makes the variable ready for grouped summaries, level inspection, and categorical analysis. section 3.4 section 6.3.2
A practical workflow is to first clean or derive a category, then convert it. For example, NBA draft picks can be placed into six ranges before the resulting character variable is converted to a factor. Values outside the intended range become `NA`, so inspect those cases before relying on the categories. section 3.4
draft2$Pk2 <- as.factor(draft2$Pk2)
Convert the derived `Pk2` draft-range variable in place after creating its six selection segments. section 3.4
Common uses include converting:
- Team, season, venue, dataset, and combined team-season labels after importing or joining game data. section 5.3 section 6.3.2
- Event labels such as play type, shot result, and free-throw type before counting or analyzing categories. section 8.4 section 16.2
- Derived labels such as season, month number, player position, or played-versus-won indicators. section 14.2.2 section 17.3
Inspecting season labels
After `pbp$data_set <- as.factor(pbp$data_set)`, call `levels(pbp$data_set)` to see its category labels. This exposes two differently spelled regular-season labels alongside a playoff label, which informs later filtering to regular-season plays only. Calling `levels()` on an unconverted character vector would return `NULL`. section 8.4
Factors also change how descriptive output is read. `summary()` reports numeric measures such as a mean and quartiles for numeric variables, but reports observation counts for factor levels. Use that distinction to validate category coverage, including unexpected blanks, alternate team names, or uneven records across seasons. section 12.4 section 13.3
