给定一个日期和它是星期几,我想知道是否有代码可以告诉我它是一个月中的哪几天。例如在下图中,给定 2/12/2020 和“星期三”,我想得到输出“2”,因为它是该月的第二个星期三。
最佳答案
您基本上可以在 base 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 包中——这样可以轻松找到“每个季度最后一个月的第三个星期三”等。
https://stackoverflow.com/questions/60211831/