liveBook · Manning

String

As explained in Statistics Slam Dunk

A character string is a sequence of text characters represented as a character value in R.

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

How Statistics Slam Dunk covers it

How deep it goes
Defines character strings and demonstrates inspection, substring extraction, and conversion to factors, dates, and numbers.
Examples
Uses NBA season labels, franchise names, play types, player names, dates, and formatted points-per-game values.
What you can do after
Apply via base R, dplyr, and stringr to inspect, extract, filter, and convert character data.
How it connects
Connects character strings with character vectors, substring operations, factor variables, date classes, numeric vectors, and data frames.

Also explained in

Compare how 24 books explain string →

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.