从随机日期开始的(下)月末
End of the (next) month from a random date
我有一个问题,从一天到月末最快的方法是什么。我有一个非常大的 table 并且我希望我的代码更快。我当前的代码如下所示:
library(lubridate)
end_of_month <- function(date){
day(date) <- days_in_month(date)
date
}
我还有一个问题。从随机日期获取下个月的最后一天是一种快速的方法吗?
"2019-05-15" %>% as.Date() %m+% months(1) %>% end_of_month # 2019-06-30
我可以一步完成吗?还是我需要一个额外的函数来处理这个?
更新答案
感谢@Edward 指出原回答中的问题。
原日期加1个月后ceiling_date
即可使用
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"
旧答案
我们可以使用 ceiling_date
和 unit
作为 '2 months'
library(lubridate)
'2019-05-15' %>% as.Date() %>% ceiling_date(unit = '2 months') - 1
#[1] "2019-06-30"
我有一个问题,从一天到月末最快的方法是什么。我有一个非常大的 table 并且我希望我的代码更快。我当前的代码如下所示:
library(lubridate)
end_of_month <- function(date){
day(date) <- days_in_month(date)
date
}
我还有一个问题。从随机日期获取下个月的最后一天是一种快速的方法吗?
"2019-05-15" %>% as.Date() %m+% months(1) %>% end_of_month # 2019-06-30
我可以一步完成吗?还是我需要一个额外的函数来处理这个?
更新答案
感谢@Edward 指出原回答中的问题。
原日期加1个月后ceiling_date
即可使用
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"
旧答案
我们可以使用 ceiling_date
和 unit
作为 '2 months'
library(lubridate)
'2019-05-15' %>% as.Date() %>% ceiling_date(unit = '2 months') - 1
#[1] "2019-06-30"