【问题标题】:How to split a date range in 5 days chunks for many years?如何将日期范围拆分为 5 天的块多年?
【发布时间】:2020-03-01 14:23:18
【问题描述】:

我正在尝试使用 googleAnalyticsR 自动向 Google Analytics 发出 API 请求。

问题在于,有这么多数据,必须将 Query 拆分成更小的块才能正确检索数据。

最后一个块应该取最后一个 API 调用的最后一天,总和 1 天。 end_date 应该是前一天。

我想要一种拆分大范围的方法,例如: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 存储库中找到了类似的代码。

它返回一个带有开始和结束日期的 df,以 montlhy 为基础。

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 天范围的块。

【问题讨论】:

    标签: r google-analytics-api


    【解决方案1】:

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

    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
    

    【讨论】:

    • 谢谢,我正在研究这段代码。现在它输出一个所有日期,当我只需要一个开始和结束日期时,5 天的大小。再次感谢您,如果您有时间,请查看我更新的问题。
    • make_ranges_day("2019-12-01", to = "2019-12-31", n = 5) 给出:Error in to - n : non-numeric argument to binary operator
    • @OmarGonzales 我忘了在第一个 if 声明中强制上课 "Date"。完成,立即查看。
    • 谢谢,我刚刚发现了另一个错误:对于n = 1,最后一个范围返回上一个日期:make_ranges_day("2019-12-01", to = "2019-12-31", n = 1) 返回:30 2019-12-30 2019-12-3031 2019-12-31 2019-12-3132 2020-01-01 2019-12-31 看看这一行。在其他情况下效果很好,ty。
    猜你喜欢
    • 1970-01-01
    • 2020-02-28
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多