Umesh Agarwal
Umesh Agarwal

Reputation: 1

Convert date formats

I have a dataframe - in which one of the column has dates in two different formats(d-m-Y and d/m/Y) and it also contains a lot of NAs. The column is of character class. I would like to change the formats of dates into one format (Y-m-d) while retaining the NAs as it is. Can you help - how can I do it in R?

Upvotes: 0

Views: 42

Answers (2)

lebatsnok
lebatsnok

Reputation: 6479

base r

You could replace "-" by "/" (or the other way round) and then use as.Date:

 df <- data.frame(Col = c("25-05-2018", "25/05/2018"), stringsAsFactors = FALSE)
 df$Col <- gsub("-", "/", df$Col)
 as.Date(df$Col, format = "%d/%m/%Y")

Upvotes: 0

akrun
akrun

Reputation: 887951

If the dates are in the same order, then use dmy from lubridate

library(lubridate)
dmy(df1$Col)
#[1] "2018-05-25" "2018-05-25"

If the orders are also different, use parse_date_time

parse_date_time(df2$Col, c("dmy", "mdy"))
#[1] "2018-05-25 UTC" "2018-05-25 UTC" "2018-05-25 UTC"

data

df1 <- data.frame(Col = c("25-05-2018", "25/05/2018"), stringsAsFactors = FALSE)
df2 <- data.frame(Col = c("25-05-2018", "25/05/2018", "5/25/2018"),
      stringsAsFactors = FALSE)

Upvotes: 2

Related Questions