【问题标题】:Convert Month to Quarter in R在 R 中将月份转换为季度
【发布时间】:2015-04-15 14:09:06
【问题描述】:

在这种情况下,如何使用 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 ...

【问题讨论】:

  • cumsum(as.numeric(Mich$Month) %% 3 == 1)

标签: r time


【解决方案1】:

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

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

dplyr

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

【讨论】:

    【解决方案2】:

    另一种方法是使用来自lubridate 库的quarter 函数:

    lubridate::quarter(Mich$Month) -> Mich$Quarter 
    

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 1970-01-01
      • 2021-10-14
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 2020-08-28
      相关资源
      最近更新 更多