繁体   English   中英

在 R 中减去日期时如何将日期舍入到该月的第一天

[英]How to round the date to the first day of the month when subtracting dates in R

我需要计算当前月份和上个月之间的差异。 我这样做

library(lubridate)
last_month <- Sys.Date() - months(1)

结果

> last_month
[1] "2022-12-04"

这是正确的答案,但我需要接收日期始终从第一天开始,例如"2022-12-01"

也就是说,四舍五入到该月的第一天?

例如,当我在 2 月 4 日执行此操作时,结果将是"2023-01-04" ,但我需要它是"2023-01-01"

像这样减去日期时如何将日期四舍五入到该月的第一天? 感谢您的帮助

您可以使用基于月份的floor_datelubridate ,如下所示:

library(lubridate)
last_month <- Sys.Date() - months(1)
floor_date(last_month, "month")
#> [1] "2022-12-01"

创建于 2023-01-04,使用reprex v2.0.2

您可以使用format ,即

format(Sys.Date() - months(1), '%Y-%m-01')
#[1] "2022-12-01"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM