Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting month abbreviations using as.Date [duplicate]

Tags:

date

r

gsub

I'm working with monthly data and have a character vector of dates, formatted:

Sep/2012
Aug/2012
Jul/2012

and so on, back to 1981. I've tried using

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

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

Note: I already found a workaround using gsub() to add "01/" in front of each entry, like so:

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

Then as.Dates() works, but this seems a little inelegant, and isn't strictly accurate anyway.

like image 817
steve Avatar asked Nov 14 '12 19:11

steve


People also ask

How do you write the date with abbreviations?

The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD.

What is the short way to write month?

The word 'months' is abbreviated to 'mos. ' The singular abbreviation of month is mo.

Do month abbreviations need a period?

Months. Abbreviations are acceptable for Jan., Feb., Aug., Sept., Oct., Nov., and Dec. Use no punctuation if listing only the month and the year, but set the year off with commas if listing the day of the month as well. The basketball game is on Thursday, Feb.

How do you abbreviate date in a letter?

In most countries of the world, dates are written in order DAY/MONTH/YEAR, e.g., 4 July 1999, abbreviated 4/7/1999. 2. In eastern Asia, however, dates are written in order YEAR/MONTH/DAY: 1999 July 4, abbreviated 1999/7/4.


1 Answers

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 to the "yearmon" class

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

Which gives

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

You can coerce to 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 a simpler way of getting the thing you did via gsub(). There is a frac argument which controls how far through the month the day component should be:

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

But that may ont be sufficient for you.

If you really only want the dates stored as you have them, then they aren't really dates but if you are happy to work within the zoo package then the "yearmon" class can be used as an index for a zoo object which is a time series.

like image 166
Gavin Simpson Avatar answered Oct 28 '22 13:10

Gavin Simpson