I have a large data set with many columns containing dates in two different formats:
\"1996-01-04\" \"1996-01-05\" \"1996-01-08\" \"1996-01-09\" \"1996-01-10
Since you know beforehand there are only two date formats, this is easy. The format
argument to as.Date
is vectorized:
as_date_either <- function(x) {
format_vec <- rep_len("%Y-%m-%d", length(x))
format_vec[grep("/", x, fixed = TRUE)] <- "%m/%d/%Y"
as.Date(x, format = format_vec)
}
Edited: replaced ifelse
with subset assignment, which is faster