Create end of the month date from a date variable

前端 未结 8 545
抹茶落季
抹茶落季 2020-12-03 06:27

I have a large data frame with date variables, which reflect first day of the month. Is there an easy way to create a new data frame date variable that represents the last d

8条回答
  •  甜味超标
    2020-12-03 07:10

    Here is another solution using the lubridate package:

    date.start.month=seq(as.Date("2012-01-01"),length=4,by="months")
    df=data.frame(date.start.month)
    
    library(lubridate)
    df$date.end.month <- ceiling_date(df$date.start.month, "month") - days(1)
    df$date.end.month
    [1] "2012-01-31" "2012-02-29" "2012-03-31" "2012-04-30"
    

    This uses the same concept given by James above, in that it gets the first day of the next month and subtracts one day.

    By the way, this will work even when the input date is not necessarily the first day of the month. So for example, today is the 27th of the month and it still returns the correct last day of the month:

    ceiling_date(Sys.Date(), "month") - days(1)
    [1] "2017-07-31"
    

提交回复
热议问题