Parse Messy Date Strings into a Date Vector in R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Write two R functions that clean up a character vector of dates written in mixed formats. You may load packages with `library()`, for example lubridate.
`parse_messy_dates(x)` returns an unnamed `Date` vector with the same length as `x`.
- It recognises only these formats, with surrounding whitespace allowed: `"YYYY-MM-DD"`, `"M/D/YYYY"`, `"Month D, YYYY"` (the comma is optional) and `"D Mon YYYY"`.
- It matches English month names and abbreviations case-insensitively and independent of the system locale, so `%B` or `%b` on their own are not enough.
- `NA`, empty, unrecognised and calendar-invalid values (month 13, `"2021-02-30"`) map to `NA` of class `Date`.
`parse_date_report(x)` returns a `data.frame` built with `stringsAsFactors = FALSE` and `length(x)` rows. Its columns are `original` (character, equal to `x`), `parsed` (Date) and `parsed_ok` (logical, `TRUE` where `parsed` is not `NA`).
For example:
```r
x <- c("2021-01-15", "1/15/2021", "January 5, 2021", " 15 Jan 2021 ", "2021-02-30", NA)
parse_messy_dates(x)
#> [1] "2021-01-15" "2021-01-15" "2021-01-05" "2021-01-15" NA NA
#> (class Date)
parse_date_report(c("1/15/2021", "nope"))
#> original parsed parsed_ok
#> 1 1/15/2021 2021-01-15 TRUE
#> 2 nope <NA> FALSE
```
```hint Classify before converting
Decide which of the four shapes a trimmed string has with an anchored pattern, and only then turn its pieces into numbers.
```
```hint Impossible dates
Once you have a year, month and day, ask whether the date you built still has that same year, month and day.
```
### What a Strong Answer Covers
- Anchored patterns for exactly the four allowed shapes, applied after trimming, with everything else mapped to `NA`.
- Month names resolved in a way that gives the same result under any system locale.
- Rejection of calendar-invalid dates such as month 13 or February 30.
- The exact return types: an unnamed `Date` vector of the input's length with typed `NA`s, and a report `data.frame` with character, Date and logical columns.
- Behaviour on `NA`, empty strings, factor input and a zero-length vector.
### Follow-up Questions
- How would you detect a format per element rather than trying all parsers on every value?
- How would you guarantee locale-independent month matching?
- How would you handle ambiguous formats like `"01/02/2021"`?
Overview: Write two R functions that turn a character vector of dates in four mixed formats into an unnamed Date vector and a per-row parse report. Tests anchored regex format detection, locale-independent month name matching, rejection of impossible calendar dates and typed NA handling.