Clean Text Columns in R With stringr
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement four text-cleaning helpers in R using `stringr`. Each one takes a character vector and returns a vector of the same length, so the result stays aligned with the column it came from.
- `extract_zip(x)`: use `str_extract` to return the first 5-digit run in each element (the leading five digits of a longer run), or `NA_character_` when there is none.
- `standardize_phone(x)`: remove every non-digit character with `str_replace_all` or `str_remove_all`, returning `""` when an element has no digits.
- `flag_valid_email(x)`: return a logical vector that is `TRUE` when `str_detect` matches exactly `^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$` and `FALSE` otherwise, including `FALSE` for `NA`.
- `clean_whitespace(x)`: trim both ends and collapse internal runs of whitespace to one space using `str_squish`.
Example:
```r
extract_zip(c("Austin TX 78701", "no zip"))
# c("78701", NA)
standardize_phone(c("(512) 555-0199", "n/a"))
# c("5125550199", "")
flag_valid_email(c("a@b.com", "bad@", NA))
# c(TRUE, FALSE, FALSE)
clean_whitespace(c(" hello world "))
# "hello world"
```
```hint Missing values
Run each helper on an `NA` element and compare what comes back with what the spec asks for. One of the four needs an explicit fix.
```
### What a Strong Answer Covers
- Each helper is vectorized and returns a result with the same length and order as its input.
- The pattern and `stringr` function chosen for each field, with regex backslashes escaped correctly inside R strings.
- How `NA` flows through each function, and the step that turns a missing email match into `FALSE`.
- Edge inputs such as digit runs longer than five, strings with no digits, empty strings, and tabs or newlines inside the text.
### Follow-up Questions
- How would you handle ZIP+4 codes like `78701-1234`?
- Why is a regex like this one insufficient for real email validation?
- What does `\d` match in a `stringr` pattern beyond the ASCII digits, and when would you write `[0-9]` instead?
Overview: Implement four vectorized R helpers with stringr that pull a 5-digit ZIP code, strip phone numbers down to digits, flag valid email addresses and squish extra whitespace. It tests regex patterns inside R strings, NA handling, and keeping each output the same length as its input.