Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Date (Year-Month) in R [duplicate]

Tags:

date

format

r

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.

like image 993
rwn1v Avatar asked Feb 20 '14 18:02

rwn1v


3 Answers

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"
like image 81
G. Grothendieck Avatar answered Oct 18 '22 08:10

G. Grothendieck


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"
like image 1
df239 Avatar answered Oct 18 '22 08:10

df239


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
like image 1
bnjmn Avatar answered Oct 18 '22 08:10

bnjmn