liveBook · Manning

Str_sub() function

As explained in Statistics Slam Dunk

The str_sub() function from stringr extracts or replaces substrings using character positions, including positions counted from the end.

str_sub() from stringr extracts a substring by specifying the character string, start position, and end position. Negative positions count from the right, making it useful for pulling fixed-width endings from messy data. section 8.4 section 14.2.2

Use str_sub() inside mutate() when a character variable needs a practical derived form:

  • Extract the seconds from play_length values such as "00:00:12" with str_sub(play_length, -2, -1), then convert the result using as.numeric(). section 8.4
  • Extract the final four characters from year values such as "w2017" with str_sub(year, -4, -1), then convert the result to a factor. section 14.2.2

NBA play duration

pbp %>% mutate(play_length2 = str_sub(play_length, -2, -1)) -> pbp pbp$play_length2 <- as.numeric(pbp$play_length2) The first values change from "00:00:00", "00:00:12", and "00:00:18" to 0, 12, and 18, producing seconds-only values for analysis. section 8.4

Readable season labels

first_stats %>% mutate(season = str_sub(year, -4, -1)) -> first_stats first_stats$season <- as.factor(first_stats$season) Values such as "w2017" become factor labels such as "2017", while the original year variable can be removed. section 14.2.2

How Statistics Slam Dunk covers it

How deep it goes
Defines three arguments, demonstrates right-to-left positions, and stops short of broader string manipulation.
Examples
Uses NBA play lengths formatted as hours:minutes:seconds and season codes such as w2017.
What it assumes
Assumes basic dplyr pipelines and R variable conversion while teaching character positions from zero.
What you can do after
Build it from scratch by extracting fixed-position text and converting the result for numeric or categorical analysis.
How it connects
Connects substring extraction with mutate(), as.numeric(), as.factor(), character vectors, and factor variables.

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.