首页 > 解决方案 > 如何将时间范围分解为每月查询?

问题描述

考虑这个简单的例子

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')),等等。

有没有一种简单的方法来使用purrrand lubridate?谢谢

标签: rlubridatepurrr

解决方案


您是否正在寻找类似的东西:

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"

这样,您可以只给出最小开始日期和最大结束日期,并获得介于两者之间的所有内容。


推荐阅读