How to find Previous Sunday in R

后端 未结 4 696
说谎
说谎 2020-12-16 14:45

It seems the Internet has not answered this question for R yet:

If I have a date. Say the 20th of march: as.Date(\"2015-03-20\") how do I get, in R, the previous Sun

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 14:54

    cut(date_var, breaks='week', start.on.monday = F)
    

    This works for me. It is available in base r and is bound to be faster. breaks can be used to find start of day, week, month, quarter, year.

    Read ?cut & ?cut.Date

    Sys.Date()
    

    [1] "2017-12-23"

    cut(Sys.Date(), breaks = 'week', start.on.monday = F)
    

    [1] 2017-12-17 Levels: 2017-12-17

    cut(Sys.Date(), breaks = 'month')
    

    [1] 2017-12-01 Levels: 2017-12-01

    cut(Sys.Date(), breaks = 'quarter')
    

    [1] 2017-10-01 Levels: 2017-10-01

    cut(Sys.Date(), breaks = 'year')
    

    [1] 2017-01-01 Levels: 2017-01-01

提交回复
热议问题