r - 如何将时间范围分解为每月查询?
问题描述
考虑这个简单的例子
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
and lubridate
?谢谢
解决方案
您是否正在寻找类似的东西:
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"
这样,您可以只给出最小开始日期和最大结束日期,并获得介于两者之间的所有内容。
推荐阅读
- javascript - Javascript:使用香草 javascript 隐藏和显示文本
- python - 从“挂起”蓝牙python连接中检测和恢复
- java - 添加新线程时的堆栈行为
- python - ValueError:时间数据“结束日期”与格式“%m/%d/%Y”不匹配
- amazon-web-services - 如何让 SQS 消息触发的 AWS Lambda 函数失败
- swift - Core Data 和 SwiftUI 多态性问题
- image - 如何使用 d3 将函数放入我的 svg 图像中?
- json - 是否可以通过对象中的值(不提供键)在表中查找记录?
- node.js - 美通 | KeenThemes 图表不工作 Laravel
- flutter - 扑。带中介的 Admob 广告