如何将日期范围分成 5 天的大块多年?

How to split a date range in 5 days chunks for many years?

我正在尝试使用 googleAnalyticsR 自动执行对 Google 分析的 API 请求。

问题是数据如此之多,必须将查询拆分成更小的块才能正确检索数据。

The last chunk should take the last day from the last API call, sum 1 day. And for the end_date it should be the day before today.

我想要一种拆分大范围的方法,例如:2017-01-012020-02-21 以 5 天为一组,并使用每个组块进行 API 调用,所以API不要崩溃。

预期data frame输出:

starts       ends
1  2017-01-01 2017-01-05
2  2017-01-06 2017-01-10
3  2017-01-11 2017-01-15
...
n  2020-02-17 today-minus-1-day

更新 1:

我在 Mark 的 github 存储库中找到了这段类似的代码。

它 returns 具有开始和结束日期的 df,以月为单位。

add_months <-  function(date, n){
  seq(date, by = paste (n, "months"), length = 2)[2]
}

make_date_ranges <- function(start, end){

  starts <- seq(from = start,
                to =  Sys.Date()-1 ,
                by = "1 month")

  ends <- c((seq(from = add_months(start, 1),
                 to = end,
                 by = "1 month" ))-1,
            (Sys.Date()-1))

  data.frame(starts,ends)

}

## useage
make_date_ranges(as.Date("2017-01-01"), Sys.Date())

最后 make_date_ranges 输出一个带有开始和结束日期的 df,以月为基础,我需要它输出 5 天的范围块。

问题编辑后,我相信以下功能可以满足问题的要求。

make_ranges_day <- function(from, to = Sys.Date(), n = 5){
  from <- as.Date(from)
  to <- if(to == Sys.Date()) Sys.Date() - 1 else as.Date(to)
  by = paste(n, "days")
  starts <- seq(from, to - n + 1, by = by)
  ends <- seq(from + n - 1, to, by = by)
  last <- length(starts)
  remaining <- to - ends[last] + 1
  if(remaining != 0){
    starts <- c(starts, ends[last] + 1)
    ends <- c(ends, to)
  }
  data.frame(starts, ends)
}

chunks <- make_ranges_day("2017-01-01")

head(chunks)
#      starts       ends
#1 2017-01-01 2017-01-05
#2 2017-01-06 2017-01-10
#3 2017-01-11 2017-01-15
#4 2017-01-16 2017-01-20
#5 2017-01-21 2017-01-25
#6 2017-01-26 2017-01-30

tail(chunks)
#        starts       ends
#225 2020-01-26 2020-01-30
#226 2020-01-31 2020-02-04
#227 2020-02-05 2020-02-09
#228 2020-02-10 2020-02-14
#229 2020-02-15 2020-02-19
#230 2020-02-20 2020-02-21