A character string is a sequence of text characters stored as a character value in R. A column such as player, franchise, or year may contain character strings, and glimpse() displays these columns with the <chr> type. section 14.2.2 section 2.3.3
Use character strings as raw text, then convert or transform them when analysis requires another representation:
- Extract text with stringr::str_sub(); extracting the final four characters from w2017 produces 2017. section 14.2.2
- Convert finite categories such as franchise, parent_child, or active_inactive to factor variables with as.factor(). section 15.2
- Convert character representations of dates or numbers before analysis, using as.Date() for yyyy-mm-dd text and as.numeric() for formatted PPG values. section 16.2 section 19.3.2
Turn season labels into usable categories
NBA records label seasons as strings such as w2017 and w2016. Create a readable season substring, remove the original year column, and convert the result to a factor for modeling or display: first_stats %>% mutate(season = str_sub(year, -4, -1)) -> first_stats first_stats %>% select(-year) -> first_stats first_stats$season <- as.factor(first_stats$season) The resulting season column contains factor values such as 2017, 2016, and 2015. section 14.2.2
first_stats %>% mutate(season = str_sub(year, -4, -1)) -> first_stats first_stats %>% select(-year) -> first_stats first_stats$season <- as.factor(first_stats$season) head(first_stats, n = 3) ## # A tibble: 3 × 3 ## Team wins season ## <chr> <int> <fct> ## 1 Atlanta Hawks 43 2017 ## 2 Atlanta Hawks 48 2016 ## 3 Atlanta Hawks 60 2015
Run the complete character-string transformation and inspect the first three rows. section 14.2.2























