I can receive files where date can be in one of the two formats: "mm/dd/yyyy" or "yyyy-mm-dd". They are factors to start with. Irrespective of the date format i receive it in, i want to be able to convert them to 'Date' data type of format "yyyy-mm-dd". I have tried using
df_1$Date <- as.Date(as.character(df_1$Date), format = "%Y-%m-%d")
This works with the format "yyyy-mm-dd" but gives NA when input values are of format "mm/dd/yyyy". Similarly, other methods i have tried works for only one of these 2 formats. I need it to work for both.
Below i have posted code for creating the datasets and replicating the issue.
df_1 <- structure(list(Text.Identifier = c(4L, 5L, 7L, 1838L), Date = structure(c(2L,
2L, 1L, 3L), .Label = c("5/18/2016", "7/12/2015", "8/29/2016"
), class = "factor")), .Names = c("Text.Identifier", "Date"), class = "data.frame", row.names = c(NA,
-4L))
df_2 <- structure(list(Text.Identifier = 1:4, Date = structure(c(5L,
5L, 5L, 1L), .Label = c("2015-07-12", "2016-05-01", "2016-05-05",
"2016-05-09", "2016-05-12", "2016-05-18", "2016-08-01", "2016-08-19",
"2016-08-29", "2016-09-20"), class = "factor")), .Names = c("Text.Identifier",
"Date"), row.names = c(NA, 4L), class = "data.frame")
df_1$Date <- as.Date(df_1$Date, format = "%Y-%m-%d")
df_2$Date <- as.Date(df_2$Date, format = "%Y-%m-%d")
View(df_1)
View(df_2)