Answers:
将format()
方法用于class对象"yearmon"
。这是您的示例日期(正确创建!)
date1 <- as.yearmon("Mar 2012", "%b %Y")
然后,我们可以根据需要提取日期部分:
> format(date1, "%b") ## Month, char, abbreviated
[1] "Mar"
> format(date1, "%Y") ## Year with century
[1] "2012"
> format(date1, "%m") ## numeric month
[1] "03"
这些作为字符返回。as.numeric()
如果希望将年份或数字月份作为数字变量,请在适当的地方包装,例如
> as.numeric(format(date1, "%m"))
[1] 3
> as.numeric(format(date1, "%Y"))
[1] 2012
请参见?yearmon
和?strftime
有关详细信息-后者解释了可以使用的占位符。
vector
n个元素,假设1k个日期,我该vector
怎么办?
date1
也可以是日期的向量。
该lubridate包是令人惊叹的这种事情:
> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012
lubridate
软件包,并尝试安装此版本并使用year(date),但它给出的是日期而不是year,这仅适用于格式为“ 2015-05”的日期-06”?
您可以使用format
:
library(zoo)
x <- as.yearmon(Sys.time())
format(x,"%b")
[1] "Mar"
format(x,"%Y")
[1] "2012"
as.numeric(format(x, "%m"))
将月份作为数字。
对于大向量:
y = as.POSIXlt(date1)$year + 1900 # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1 # x$mon : 0–11
POSIXlt
对象,使得不需要动物园包裹