在R中将月份转换为季度

时间:2015-04-15 14:09:07

标签: r time

在这种情况下,如何使用mutate添加列将月份转换为季度?

Month   Year    Michigan.OnPk   PX_LAST
  01    2012    29.64900    2.707800
  02    2012    30.91400    2.525950
  03    2012    29.60727    2.295591
  04    2012    31.63800    2.048200
  05    2012    35.39682    2.493409
  06    2012    37.37286    2.498238
  07    2012    55.50667    2.963190
  08    2012    37.62304    2.807435
  09    2012    31.29000    2.917737
  10    2012    33.77455    3.490818
  11    2012    36.42619    3.687333
  12    2012    32.87300    3.444150

数据框的结构:

str(Mich)
'data.frame':   39 obs. of  4 variables:
 $ Month        : chr  "01" "02" "03" "04" ...
 $ Year         : chr  "2012" "2012" "2012" "2012" ...
 $ Michigan.OnPk: num  29.6 30.9 29.6 31.6 35.4 ...
 $ PX_LAST      : num  2.71 2.53 2.3 2.05 2.49 ...

1 个答案:

答案 0 :(得分:1)

简单的方法是执行以下操作

Mich$Quarter <- ceiling(as.numeric(Mich$Month) / 3)

dplyr

Mich <- Mich %>% mutate(Quarter = ceiling(as.numeric(Mich$Month) / 3))