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

被刻印的时光 ゝ 提交于 2020-01-17 03:07:49

问题


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.


回答1:


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"



回答2:


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"



回答3:


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


来源:https://stackoverflow.com/questions/37552688/converting-character-into-a-date-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!