Lb93
Lb93

Reputation: 191

Formatting dates with only month and year in R

I have quite a simple problem that I've not found anywhere on here.

I have date format:

times = c("Dec_2011" , "July_2011", "Dec_2010"  ,"July_2010" , "Dec_2009" , "July_2009", "Dec_2008" ,
                     "July_2008" ,"Dec_2007" , "July_2007", "Dec_2006" , "July_2006" ,"Dec_2005" , "July_2005",
                     "Dec_2004" , "July_2004" ,"Dec_2003" , "July_2003", "Dec_2002" , "July_2002", "Dec_2001" ,
                     "July_2001", "Dec_2000" , "July_2000")

How can I get these into date format:

31-07-2000, 31-07-2001, etc...
31-12-2000, 31-12-2001, etc...

I've tried:

times <- format(as.Date(time, "%B_%Y")
times
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA


times <- format(as.Date(time, "%B_%Y), "31-%m-%Y)
times
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

times <- as.Date(paste("31", times, sep="-"), "%d-%m-%Y")
times
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

times <- format(as.Date(time, "%b_%Y"), "31-%m-%Y")
# NA

I'm not quite sure how to proceed.

Upvotes: 1

Views: 998

Answers (1)

akrun
akrun

Reputation: 887118

If we need 31 as the day for all the elements, use paste to join 31, convert to Date class and get the desired format with format.

format(as.Date(paste(times, "31", sep="_"), "%b_%Y_%d"), "%d-%m-%Y")
#[1] "31-12-2011" "31-07-2011" "31-12-2010" "31-07-2010" "31-12-2009" "31-07-2009" "31-12-2008" "31-07-2008" "31-12-2007" "31-07-2007" "31-12-2006"
#[12] "31-07-2006" "31-12-2005" "31-07-2005" "31-12-2004" "31-07-2004" "31-12-2003" "31-07-2003" "31-12-2002" "31-07-2002" "31-12-2001" "31-07-2001"
#[23] "31-12-2000" "31-07-2000"

Instead of manually pasteing 31, we can automate this with as.yearmon from zoo. The advantage is that for months that have less than 31 days, we get the last day by doing that.

library(zoo)
format(as.Date(as.yearmon(times, "%b_%Y"), frac=1), "%d-%m-%Y")
#[1] "31-12-2011" "31-07-2011" "31-12-2010" "31-07-2010" "31-12-2009" "31-07-2009" "31-12-2008" "31-07-2008" "31-12-2007" "31-07-2007" "31-12-2006"
#[12] "31-07-2006" "31-12-2005" "31-07-2005" "31-12-2004" "31-07-2004" "31-12-2003" "31-07-2003" "31-12-2002" "31-07-2002" "31-12-2001" "31-07-2001"
#[23] "31-12-2000" "31-07-2000"

Upvotes: 1

Related Questions