从Zoo :: yearmon对象中提取月份和年份


112

我有一个yearmon对象:

require(zoo)
date1 <- as.yearmon("Mar 2012", "%b %Y")
class(date1)
# [1] "yearmon"

如何从中提取月份和年份?

month1 <- fn(date1)
year1 <- fn(date1)

我应该用什么功能代替 fn()

Answers:


143

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有关详细信息-后者解释了可以使用的占位符。


4
%B表示整月,即3月“代替”“ Mar”
PatrickT

如果有vectorn个元素,假设1k个日期,我该vector怎么办?
Stophface 2015年

像R一样,@ Chrissl date1也可以是日期的向量。
加文·辛普森

101

lubridate包是令人惊叹的这种事情:

> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012

2
哈谢谢你的回答。当您要执行if(year(date1)> 2014){year(date1)<-year(date1)-100}
Vincent

1
这绝对是我从4000个合同的开始日期中提取年份的要求的最佳答案。
d8aninja'3

@Ari B. Friedman我目前正在使用R 3.1.0,但此版本不支持lubridate软件包,并尝试安装此版本并使用year(date),但它给出的是日期而不是year,这仅适用于格式为“ 2015-05”的日期-06”?
KRU 2015年

1
@KRU新版本的R有时需要几个星期才能使存储库更新所有软件包。只要它是真实的日期格式,而不是字符向量,它就应该适用于所有日期格式。如果仍然不能解决您的问题,并且您无法在SO中搜索问题的任一部分,请发布新的q。
阿里·弗里德曼

15

我知道OP zoo在这里使用,但是我发现该线程在搜索ts同一问题的标准解决方案。所以我想我也要添加一个zoo-free答案ts

# create an example Date 
date_1 <- as.Date("1990-01-01")
# extract year
as.numeric(format(date_1, "%Y"))
# extract month
as.numeric(format(date_1, "%m"))

12

您可以使用format

library(zoo)
x <- as.yearmon(Sys.time())
format(x,"%b")
[1] "Mar"
format(x,"%Y")
[1] "2012"

我怎样才能使月份成为数字?(例如3月3日?)
adam.888 2012年

@ user1169210我在回答中提到了这一点。例如,您想as.numeric(format(x, "%m"))将月份作为数字。
加文·辛普森

5

对于大向量:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11

1
这是最好的答案,因为R已经提供了方便的POSIXlt对象,使得不需要动物园包裹
Marco Demaio

0

该问题并未精确说明预期的输出结果,但假设对于月份,您想要月份数字(January = 1),对于年份,则想要数字4位数字年份,然后假设我们刚刚运行了问题中的代码:

cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012

0

从1800到现在,在数据方面也遇到过类似的问题,这对我有用:

data2$date=as.character(data2$date) 
lct <- Sys.getlocale("LC_TIME"); 
Sys.setlocale("LC_TIME","C")
data2$date<- as.Date(data2$date, format = "%Y %m %d") # and it works
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.