Formatting Month Abbreviations Using as.Date

I work with monthly data and have a date symbol vector, formatted:

Sep/2012 Aug/2012 Jul/2012 

etc., until 1981. I tried using

 as.Date(dates, "%b/%Y") 

where %b represents the abbreviations of the month, but this only returns NA. What am I doing wrong?

Note. I already found a workaround using gsub() to add "01 /" before each entry, for example:

 01/Sep/2012 01/Aug/2012 01/Jul/2012 

Then as.Dates() works, but it seems a little inelegant, and in any case, it is not strictly accurate.

+6
source share
1 answer

You are looking for as.yearmon() in the zoo package. Given your dates

 dates <- c("Sep/2012","Aug/2012","Jul/2012") 

we load the package and convert it to the "yearmon" class

 require(zoo) dates1 <- as.yearmon(dates, format = "%b/%Y") dates1 

What gives

 R> dates1 [1] "Sep 2012" "Aug 2012" "Jul 2012" 

You can force an object of class "Date" using the as.Date() method

 R> as.Date(dates1) [1] "2012-09-01" "2012-08-01" "2012-07-01" 

Which would be an easier way to get what you did through gsub() . There is a frac argument that determines how far in a month the day component should be:

 R> as.Date(dates1, frac = 0.5) [1] "2012-09-15" "2012-08-16" "2012-07-16" 

But this may not be enough for you.

If you really want the dates stored as they are, then they are not dates, but if you are happy to work in the zoo package, then you can use the "yearmon" class as an index for the zoo object, which is a time series.

+8
source

All Articles