从随机日期开始的(下一个)月末

Kyo*_*oto 2 r date lubridate dplyr

我有一个问题,从一天开始到月底的最快方法是什么。我有一个非常大的表,我希望我的代码很快。我当前的代码如下所示:

library(lubridate)

end_of_month <- function(date){
 day(date) <- days_in_month(date)
 date
}
Run Code Online (Sandbox Code Playgroud)

我有另一个问题。从随机日期获取下个月的最后一天是一种快速的方法吗?

"2019-05-15" %>% as.Date() %m+% months(1) %>% end_of_month  # 2019-06-30
Run Code Online (Sandbox Code Playgroud)

我可以一步完成还是需要一个额外的功能来处理这个问题?

Ron*_*hah 5

更新答案

感谢@Edward 在原始答案中指出了这个问题。

您可以ceiling_date在原始日期增加 1 个月后使用

ceiling_date(as.Date('2019-05-15') + months(1), unit = "month") - 1
#[1] "2019-06-30"

ceiling_date(as.Date('2019-04-15') + months(1), unit = "month") - 1
#[1] "2019-05-31"
Run Code Online (Sandbox Code Playgroud)

旧答案

我们可以使用ceiling_dateunit作为'2 months'

library(lubridate)
'2019-05-15' %>% as.Date() %>% ceiling_date(unit = '2 months') - 1
#[1] "2019-06-30"
Run Code Online (Sandbox Code Playgroud)