Extract first Monday of every month

后端 未结 3 1348
无人及你
无人及你 2021-01-13 14:17

How can I extract the first Monday of every month from 2010-01-01 to 2015-12-31?

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-13 14:18

    We can use lubridate, wday to test if this is a Monday, and day to test if this is the first week of the month:

    library(lubridate)
    x <- seq(ymd("2010-01-01"),ymd("2015-12-31"),by="1 day")
    x[wday(x,label = TRUE) == "Mon" & day(x) <= 7]
    

    or in base-r (@DavidArenburg's comment)

    x <- seq(as.Date("2010-01-01"), as.Date("2015-12-31"), by = "day")
    # You need to adapt "Monday" to the equivalent in your locale
    x[weekdays(x) == "Monday" & as.numeric(format(x, "%d")) <= 7]
    

    output (five first results)

    [1] "2010-01-04 UTC" "2010-02-01 UTC" "2010-03-01 UTC" "2010-04-05 UTC" "2010-05-03 UTC" "2010-06-07 UTC"
    

提交回复
热议问题