将日期转换成年季度格式 [英] Convert date to year-quarter format
本文介绍了将日期转换成年季度格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一堆日期格式为 yyyy-mm-dd
的日期,我想将它们转换为 yyyy-q
格式,其中qq
是一年的四分之一(因此,第1、2、3个月映射到q = 1,第4、5、6个月映射到q = 2,依此类推).我使用以下功能来实现这一点:
I have a bunch of dates that are of the format yyyy-mm-dd
and I would like to convert them to a yyyy-q
format where qq
is the quarter of the year (so months 1, 2, 3 map to q=1 and 4, 5, 6 map to q=2, etc.). I use the following function to accomplish this:
get_month <- function(d) { return(as.numeric(format(d, "%m")))}
get_qtr <- function(d) {
f <- function(m) {
if (m %in% c(1,2,3)) { return(1) }
else if (m %in% c(4,5,6)) { return(2) }
else if (m %in% c(7,8,9)) { return(3) }
else if (m %in% c(10,11,12)) { return(4) }
}
m <- get_month(d)
r <- sapply(m, f)
return(r)
}
但是,这非常慢.有更快的方法吗?
This is, however, very slow. Is there a faster way of doing this?
推荐答案
您可以在Zoo软件包中使用 yearqtr
.
You can use yearqtr
in the zoo package.
> as.yearqtr(Sys.Date())
[1] "2012 Q4"
这篇关于将日期转换成年季度格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文