将数字日期格式(YYYYMMDD; 20150101)转换为年-月 [英] Convert numeric date format (YYYYMMDD; 20150101) into Year-Month
问题描述
你们中的任何人都可以帮助将日期从 20150101
转换为缩写形式 2015年1月
吗?
Can anyone of you help in converting the date from 20150101
to abbreviated form Jan-2015
?
我尝试了以下方法。
x = 20150101
zoo::as.yearmon(x, "%b-%y")
但是我得到了以下内容错误
But I got the below error
charToDate(x)中的错误:
字符串不是标准的明确格式
Error in charToDate(x) : character string is not in a standard unambiguous format
任何帮助将不胜感激。
推荐答案
有问题中的代码有两个问题:
There are two problems with the code in the question:
-
输入格式指定为
%b -%y ,但应为
%y%m
我们希望在此处使用 as.yearmon.character
,而不是
<$ c $ as.yearmon.numeric ,因此输入应转换为
字符
we wish to use as.yearmon.character
here rather than
as.yearmon.numeric
so the input should be converted to
"character"
因此,请尝试以下操作:
Therefore, try this:
library(zoo)
ym <- as.yearmon(as.character(20150101), "%Y%m")
给予:
> ym
[1] "Jan 2015"
请注意 yearmon
对象内部存储为年+分数,其中分数对于1月为0,对于1月为1/12,对于2月为...,对于12月为11/12。在外部,它们被表示为缩写月份,后跟
Note that "yearmon"
objects are internally stored as year + fraction where fraction is 0 for Jan, 1/12 for Feb, ..., 11/12 for Dec. Externally they are rendered as an abbreviated month followed by a space and the year as shown.
上面的内容可能就足够了,但是如果不将其转换为格式为%b- %y 或
%b-%Y
使用格式
:
The above may be sufficient but if not to convert it to a character string with format "%b-%y"
or "%b-%Y"
use format
:
format(ym, "%b-%y")
## [1] "Jan-15"
format(ym, "%b-%Y")
## [1] "Jan-2015"
这篇关于将数字日期格式(YYYYMMDD; 20150101)转换为年-月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!