简体   繁体   中英

Identify if a day of the week is 2nd/3rd etc Mon/Tues/etc day of the month in R

Given a date and the day of the week it is, I want to know if there is a code that tells me which of those days of the month it is. For example in the picture below, given 2/12/2020 and "Wednesday" I want to be given the output "2" for it being the second Wednesday of the month.

样本

You can do that in base R in essentially one operation. You also do not need the second input column.

Here is slower walkthrough:

Code

dates <- c("2/12/2020","2/11/2020","2/10/2020","2/7/2020","2/6/2020", "2/5/2020")
Dates <- anytime::anydate(dates)   ## one of several parsers
dow   <- weekdays(Dates)           ## for illustration, base R function
cnt   <- (as.integer(format(Dates, "%d")) - 1) %/% 7 + 1

res <- data.frame(dt=Dates, dow=dow, cnt=cnt)
res

(Final) Output

R> res
          dt       dow cnt
1 2020-02-12 Wednesday   2
2 2020-02-11   Tuesday   2
3 2020-02-10    Monday   2
4 2020-02-07    Friday   1
5 2020-02-06  Thursday   1
6 2020-02-05 Wednesday   1
R> 

Functionality like this is often in dedicated date/time libraries. I wrapped some code from the (C++) Boost date_time library in package RcppBDH -- that allowed to easily find 'the third Wednesday in the last month each quarter' and alike.

(lubridate::day(your_date) - 1) %/% 7 + 1

The idea here is that the first 7 days of the month are all the first for their weekday. Next 7 are 2nd, etc.

> (1:30 - 1) %/% 7 + 1
# [1] 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5

Just to offer an alternative calculation for the nth-weekday of the month, you can just divide the day by 7 and always round up:

date <- lubridate::mdy("02/12/2020")
ceiling(day(date)/7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM