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
