简体   繁体   English

确定一周中的某一天是否是 R 中的第 2/3 日等星期一/星期二/等

[英]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.例如在下图中,给定 2/12/2020 和“星期三”,我希望得到输出“2”,因为它是本月的第二个星期三。

样本

You can do that in base R in essentially one operation.您基本上可以在一个操作中在基础 R 中做到这一点。 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.我将来自 (C++) Boost date_time 库的一些代码封装在 RcppBDH 包中——这样可以轻松找到“每个季度上个月的第三个星期三”等。

(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.这里的想法是一个月的前 7 天都是工作日的第一天。 Next 7 are 2nd, etc.接下来的 7 个是第二个,以此类推。

> (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:只是为了提供一个月的第 n 个工作日的替代计算,您可以将这一天除以 7 并始终向上取整:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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