从 %Y - %Q 形式的日期获取第一个月和最后一个月

Obtain first and last month from a date of the form %Y - %Q

我从 data.frame 开始,我将 x 列转换为年份和季度。

library(data.table)
library(dplyr)
library(zoo)

data = data.frame(x = c("2017-12-01", 
                       "2017-12-01", 
                       "2017-11-01", 
                       "2017-11-01", 
                       "2017-10-01", 
                       "2017-10-01"))

data <- data %>% 
  mutate(x = as.Date(x, format = "%Y-%m-%d"),
                     x = as.yearqtr(x))

我想要实现的是使用两个新列 start_atend_at 切换 x,其中 start_at 采用 2017-first month of quarter-01 的形式, end_at 采用形式 2017-last month of the quarter-01.

我想要达到的目标:

data = data.frame(start_at = "2017-10-01", end_at = "2017-12-01")
library(lubridate)
do.call(rbind, lapply(unique(data$x), function(d)
    data.frame(start_at = as.Date(d),
               end_at = floor_date(x = as.Date(as.yearqtr(as.numeric(d) + .25)) - 1,
                                   unit = "months"))))
#    start_at     end_at
#1 2017-10-01 2017-12-01

您也可以使用 as.yearmon 的可选 frac 参数在没有 lubridate 的情况下实现它(G. Grothendieck 在评论中建议)。

"frac" which is a number between 0 and 1 inclusive that indicates the fraction of the way through the period that the result represents

frac = 1 表示周期结束(在本例中为 Q4)。

do.call(rbind, lapply(unique(data$x), function(d)
    data.frame(start_at = as.Date(d), end_at = as.Date(as.yearmon(d, frac = 1)))))
#    start_at     end_at
#1 2017-10-01 2017-12-01