ganesh nair
ganesh nair

Reputation: 1

Converting Date Columns in R ("character" into Date format)

I have a sample date column as part of large data set, Below date is in multiple format.

I need convert below mentioned into Date format , Please help me with a solution.

22-04-2015 4/8/2015 18-04-2015 5/7/2015 26-05-2015 6/12/2015 24-06-2015 23-06-2015

Upvotes: 0

Views: 174

Answers (2)

sreedta
sreedta

Reputation: 133

Have you tried to use R package anytime for date conversion?

> library(anytime)
> datemix <- c("22-04-2015", "4/8/2015", "18-04-2015", "5/7/2015")
> anydate(datemix)
[1] NA "2015-04-08" NA "2015-05-07"

You notice that the first and third character dates came up with NA. This is because the package anytime as currently defined does not include this format "d-m-y". It is very easy to add this format with the addFormats() command as shown below

> addFormats("%d-%m-%Y")
> datemix <- c("22-04-2015", "4/8/2015", "18-04-2015", "5/7/2015")
> anydate(datemix)
[1] "2015-04-22" "2015-04-08" "2015-04-18" "2015-05-07"

The output dates are converted into ISO format of YYYY-MM-DD.

You can explore all the formats in anytime using getFormats() command. Here is the link to the anytime on R CRAN https://cran.r-project.org/web/packages/anytime/anytime.pdf

Upvotes: 0

Duck
Duck

Reputation: 39613

Try with lubridate. The function guess_formats() allows defining possible formats of your data (you could add others if needed), and then you can use as.Date() to get the dates in the proper class using the formats previously defined. Here the code:

library(lubridate)
#Dates
vecdate <- c('22-04-2015', '4/8/2015','18-04-2015','5/7/2015','26-05-2015',
             '6/12/2015','24-06-2015','23-06-2015')
#Formats
formats <- guess_formats(vecdate, c("dmY"))
dates <- as.Date(vecdate, format=formats)

Output:

dates
 [1] "2015-04-22" "2015-08-04" "2015-04-18" "2015-07-05" "2015-05-26" "2015-12-06" "2015-06-24"
 [8] "2015-06-23" "2015-04-22" "2015-08-04" "2015-04-18" "2015-07-05" "2015-05-26" "2015-12-06"
[15] "2015-06-24" "2015-06-23"

Upvotes: 1

Related Questions