Here's a robust and flexible function to clean Excel dates in R using tidyverse, specifically targeting columns with "date" in their names and converting them to POSIXct format:
✅ Function Overview
- Handles Excel numeric dates (e.g., 44927 → 2023-01-01).
- Parses character dates with multiple common formats (e.g., "2023-01-01", "01/01/2023", "01-01-2023").
- Converts to
POSIXct for unified datetime handling.
- Applies to all columns containing "date" in their names.
📦 Dependencies
Ensure you have the following packages installed:
install.packages("tidyverse")
install.packages("lubridate")
🧠 Function Code
library(tidyverse)
library(lubridate)
clean_excel_dates <- function(x) {
# Convert factors to character
x <- if (is.factor(x)) as.character(x) else x
# Handle numeric Excel dates (convert to Date, then to POSIXct)
if (is.numeric(x)) {
return(as.POSIXct(as.Date(x, origin = "1899-12-30")))
}
# Handle character dates with multiple formats
if (is.character(x)) {
parsed <- parse_date_time(
x,
c("ymd", "dmy", "mdy", "Y-m-d", "m/d/Y", "d/m/Y", "d-M-Y", "M/d/Y")
)
return(as.POSIXct(parsed))
}
# Return original for non-date columns
x
}
📊 Usage Example
# Example dataframe
df <- tibble(
id = 1:3,
birth_date = c(44927, "1990-05-15", "05/15/1990"),
created_at = c("2023-01-01", "2023/02/01", "02-01-2023"),
other_column = c("A", "B", "C")
)
# Apply the function to all columns with "date" in the name
df_clean <- df %>%
mutate(across(where(~ str_detect(cur_column(), "date")), clean_excel_dates))
# View results
print(df_clean)
📌 Notes
- Excel numeric dates are converted using
origin = "1899-12-30" (correct for Excel).
- Character dates are parsed with
lubridate::parse_date_time using multiple common formats.
- Non-date columns (e.g., "other_column") remain unchanged.
- If some dates fail to parse, they will become
NA. You can handle this with na.omit() or custom logic.
🔍 Customization Tips
- Add more date formats to
parse_date_time if your data has unique patterns.
- Use
tryCatch() or ifelse() to handle errors gracefully if needed.
This solution is efficient, extensible, and leverages tidyverse best practices for data cleaning.