代码之家  ›  专栏  ›  技术社区  ›  ℕʘʘḆḽḘ

如何将时间范围划分为每月查询?

  •  0
  • ℕʘʘḆḽḘ  · 技术社区  · 6 年前

    考虑这个简单的例子

    bogus <- function(start_time, end_time){
      print(paste('hey this starts on', start_time, 'until', end_time))
    }
    
    start_time <- ymd('2018-01-01')
    end_time <- ymd('2018-05-01')
    
    > bogus(start_time, end_time)
    [1] "hey this starts on 2018-01-01 until 2018-05-01"
    

    不幸的是,在很长的时间范围内这样做并不适用于我的现实生活 bogus 函数,所以我需要将原始时间范围分解为每月的片段。

    换句话说,第一个电话是 bogus(ymd('2018-01-01'), ymd('2018-01-31')) ,第二个 bogus(ymd('2018-02-01'), ymd('2018-02-28')) 等。

    有什么简单的方法可以用吗 purrr lubridate ? 谢谢

    2 回复  |  直到 6 年前
        1
  •  3
  •   iod    6 年前

    带底座:

    seqdate<-seq.Date(start_time,end_time,by="1 month")
    dateranges<-data.frame(start.dates=seqdate[1:length(seqdate)-1], 
      end.dates=seqdate[2:length(seqdate)]-1)
    
      start.dates  end.dates
    1  2018-01-01 2018-01-31
    2  2018-02-01 2018-02-28
    3  2018-03-01 2018-03-31
    4  2018-04-01 2018-04-30
    
        2
  •  4
  •   arg0naut91    6 年前

    你在找类似的东西吗?

    library(lubridate)
    
    seq_dates <- seq(start_time, end_time - 1, by = "month")
    
    lapply(seq_dates, function(x) print(paste('hey this starts on', x, 'until', ceiling_date(x, unit = "month") - 1)))
    

    你也可以做一个简短的伪函数,比如:

    bogus <- function(start_var, end_var) {
    
     require(lubridate)
    
     seq_dates <- seq(as.Date(start_var), as.Date(end_var) - 1, by = "month")
    
     printed_statement <- lapply(seq_dates, function(x) paste('hey this starts on', x, 'until', ceiling_date(x, unit = "month") - 1))
    
     for (i in printed_statement) { print(i) }
    
    }
    

    就像这样称呼它:

    bogus("2018-01-01", "2018-05-01")
    

    输出:

    [1] "hey this starts on 2018-01-01 until 2018-01-31"
    [1] "hey this starts on 2018-02-01 until 2018-02-28"
    [1] "hey this starts on 2018-03-01 until 2018-03-31"
    [1] "hey this starts on 2018-04-01 until 2018-04-30"
    

    这样,您就可以给出最小开始日期和最大结束日期,并在两者之间找到所有内容。