r如何从日期中提取季度

  • 本文关键字:提取 季度 日期
  • 更新时间 :
  • 英文 :


为什么"3个月"的切割没有产生预期的标签?

 # create time series data
 everyday <- seq(from = as.Date('2014-1-1'), to = as.Date('2014-12-31'), by = 'day')
 # create a factor based on the quarter of the year an observation is in:
 qtrs <- cut(everyday, "3 months", labels = paste0('Q', 1:4))
 ## Error in cut.default(unclass(x), unclass(breaks), labels = labels, 
 ## right = right,  : 
 ##   lengths of 'breaks' and 'labels' differ

切割每3个月一次,因此将创建4个季度,我预计需要4个标签,但错误消息表明中断和标签的长度不同。

 qtrs <- cut(everyday, "3 months", labels = paste0('Q', 1:5))
 table(qtrs)
 ## qtrs
 ## Q1 Q2 Q3 Q4 Q5 
 ## 90 91 92 92  0 

第五个标签Q5似乎是需要的,但却以零计数出现。

示例取自的Phil Spector的"R数据操作"

http://www.springer.com/statistics/computational+统计学/book/978-0-387-74730-9

这并不能回答您最初的问题,而是在没有cut的情况下实现(我认为是)相同结果的一种方法。您可以使用quarters函数从Date对象提取"四分之一":

table(quarters(everyday))
# Q1 Q2 Q3 Q4 
# 90 91 92 92

最新更新