R中最近的月末

nearest month end in R

您好,我想为 R 中的日期列查找最近的月末。

有什么有效的方法吗?

dt<-data.frame(orig_dt=as.Date(c("1997-04-01",
      "1997-06-29"
)))


dt<-dt %>% mutate(modified_dt="Nearest_month_end_date")

即 1997-04-01 应更改为 1997-03-31,1997-06-29 应更改为 1997-06-30。

试试这个:

library(lubridate)
dt<-dt %>% mutate(modified_dt=round_date(orig_dt, unit="month")-days(1))

#Output
> dt
     orig_dt modified_dt
1 1997-04-01  1997-03-31
2 1997-06-29  1997-06-30