0

Hi I want to find the nearest month end for a date column in R.

Is there any efficient way to do this?

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


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

ie 1997-04-01 should change to 1997-03-31 and 1997-06-29 should change to 1997-06-30.

itthrill
  • 1,241
  • 2
  • 17
  • 36

1 Answers1

6

Try this:

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
phalteman
  • 3,442
  • 1
  • 29
  • 46