How to flag last friday or last day or month

前端 未结 4 613
慢半拍i
慢半拍i 2021-01-22 17:53

I have a data frame of dates and the day of the week

> head(data)
         day   weekday
1 2016-01-01    Friday
4 2016-01-04    Monday
5 2016-01-05   Tuesday
         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-22 18:01

    With the additional clarification and following the comment by @eminik the code below

    library(data.table)
    setDT(data)
    data[, LastDayInMonth := day == max(day), by = .(year(day), month(day))]
    data[, LastFridayInMonth := weekday == "Friday" & day == max(day), 
         by = .(year(day), month(day), weekdays(day))]
    

    produces:

    # show results (only relevant rows)
    data[LastDayInMonth | LastFridayInMonth == TRUE]
    
              day  weekday LastDayInMonth LastFridayInMonth
    1: 2016-01-29   Friday           TRUE              TRUE
    2: 2016-02-26   Friday          FALSE              TRUE
    3: 2016-02-29   Monday           TRUE             FALSE
    4: 2016-03-25   Friday          FALSE              TRUE
    5: 2016-03-31 Thursday           TRUE             FALSE
    6: 2016-04-29   Friday           TRUE              TRUE
    7: 2016-05-06   Friday          FALSE              TRUE
    8: 2016-05-10  Tuesday           TRUE             FALSE
    

    Edit: Code modified to account for change of years as requested by OP.

    Note: weekdays returns a character vector of names in the locale in use. Therefore, the code only works if you are in an English locale. Otherwise, you may have to use Sys.setlocale(category = "LC_ALL", locale = "English") before.

提交回复
热议问题