Create end of the month date from a date variable

前端 未结 8 546
抹茶落季
抹茶落季 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:02

    A straightforward solution would be using the yearmonfunction with the argument frac=1 from the xts-package. frac is a number between 0 and 1 that indicates the fraction of the way through the period that the result represents.

    as.Date(as.yearmon(seq.Date(as.Date('2017-02-01'),by='month',length.out = 6)),frac=1)
    
    [1] "2017-02-28" "2017-03-31" "2017-04-30" "2017-05-31" "2017-06-30" "2017-07-31"
    

    Or if you prefer “piping” using magrittr:

    seq.Date(as.Date('2017-02-01'),by='month',length.out = 6) %>%
             as.yearmon() %>% as.Date(,frac=1)
    
    [1] "2017-02-28" "2017-03-31" "2017-04-30" "2017-05-31" "2017-06-30" "2017-07-31"
    

提交回复
热议问题