[英]Identify if a day of the week is 2nd/3rd etc Mon/Tues/etc day of the month in R
您基本上可以在一個操作中在基礎 R 中做到這一點。 您也不需要第二個輸入列。
這是較慢的演練:
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
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>
像這樣的功能通常在專用的日期/時間庫中。 我將來自 (C++) Boost date_time 庫的一些代碼封裝在 RcppBDH 包中——這樣可以輕松找到“每個季度上個月的第三個星期三”等。
(lubridate::day(your_date) - 1) %/% 7 + 1
這里的想法是一個月的前 7 天都是工作日的第一天。 接下來的 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
只是為了提供一個月的第 n 個工作日的替代計算,您可以將這一天除以 7 並始終向上取整:
date <- lubridate::mdy("02/12/2020")
ceiling(day(date)/7)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.