Find most recent Monday for a dataframe

前端 未结 6 594
甜味超标
甜味超标 2021-01-15 02:35

I have a dataframe object, and among the fields in it, I have a dates:

df$dates

I need to add a column which is \'Week Starting\', i.e.

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 02:55

    How about just subtracting from the dates the number of days required to get to the previous Monday? e.g if your data is

    dates <- as.Date(c("2000-07-12", "2005-02-19", "2010-09-01"))
    weekdays(dates)
    # [1] "Wednesday" "Saturday"  "Wednesday"
    

    then you can compare this to a vector

    wdays <- setNames(0:6, c("Monday", "Tuesday", "Wednesday",
                "Thursday", "Friday", "Saturday", "Sunday"))
    

    and subtract the required number of days from each date, ie

    dates - wdays[weekdays(dates)]
    #   Wednesday     Saturday    Wednesday 
    #"2000-07-10" "2005-02-14" "2010-08-30" 
    

    will give the dates of the Monday preceding each date in dates. To test:

    weekdays(dates - wdays[weekdays(dates)])
    #Wednesday  Saturday Wednesday 
    # "Monday"  "Monday"  "Monday" 
    

    Everything can be written also in one line as

    dates - match(weekdays(dates), c("Monday", "Tuesday", "Wednesday", 
       "Thursday", "Friday", "Saturday", "Sunday")) + 1
    #"2000-07-10" "2005-02-14" "2010-08-30" 
    

提交回复
热议问题