7

Is it possible to format the following number to Year-Month I entries as follows:

1402 1401 1312

Meaning February 2014. January 2014 and December 2013.

I tried:

date <- 1402
date <- as.Date(as.character(date), format = "%y%m")

But I get an NA as an output.

rwn1v
  • 777
  • 3
  • 10
  • 23

3 Answers3

17

The zoo package has a "yearmon" class that directly handles year/month objects:

library(zoo)
nums <- c(1402, 1401, 1312)
ym <- as.yearmon(as.character(nums), "%y%m")

giving:

> ym
[1] "Feb 2014" "Jan 2014" "Dec 2013"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

You need to include day number, otherwise it is impossible to understand what day of month you have in mind, consider:

> strptime('011402', format = "%d%y%m")
[1] "2014-02-01"
df239
  • 471
  • 2
  • 4
1

as.Date requires a full date, with day specified. Since you don't include a day it doesn't know what to do.

You could add any day and it should work like this

date <- 140201
date <- as.Date(as.character(date), format="%y%m%d")

You could use the lubridate package to work with date a little bit easier.

> library(lubridate)
> month(ymd(as.character(140201), label=TRUE)
[1] February
bnjmn
  • 4,508
  • 4
  • 37
  • 52