I have a variable with dates in a two different formats ("%Y-%m-%d"
and "%m/%d/%Y"
):
dput(df)
structure(1:8, .Label = c("2019-04-07", "2019-04-08", "2019-04-09",
"2019-04-10", "7/29/2019", "7/30/2019", "7/31/2019", "8/1/2019"
), class = "factor")
# [1] 2019-04-07 2019-04-08 2019-04-09 2019-04-10 7/29/2019 7/30/2019 7/31/2019 8/1/2019
# 8 Levels: 2019-04-07 2019-04-08 2019-04-09 2019-04-10 7/29/2019 7/30/2019 ... 8/1/2019
I try to parse the dates using as.Date
with tryFormats
df <- as.character(df)
d <- as.Date(df, tryFormats = c("%Y-%m-%d", "%m/%d/%Y"))
which converts the first format structure, but then returns NA
for the second format structure. If I run the two formats separately, they look good though:
t1 <- as.Date(df, format = "%Y-%m-%d")
t2 <- as.Date(df, format = "%m/%d/%Y")
t1
# [1] "2019-04-07" "2019-04-08" "2019-04-09" "2019-04-10" NA
# [6] NA NA NA
t2
# [1] NA NA NA NA "2019-07-29"
# [6] "2019-07-30" "2019-07-31" "2019-08-01"
Any suggestions? I've looked through other responses, but haven't found any good tryFormats examples/questions that seem to address this.