简体   繁体   English

在 R 中查找每个月第三周的最后一天

[英]Finding the last day of 3rd week for each month in R

I have a vector that contains dates.我有一个包含日期的向量。 I want to find the dates which are the last day of the 3rd week for each month.我想找到每个月第三周的最后一天的日期。

structure(c(18631L, 18632L, 18633L, 18634L, 18635L, 18638L, 18639L, 18640L, 18641L, 18642L, 18645L, 18646L, 18647L, 18648L, 18649L, 18651L, 18652L, 18653L, 18654L, 18655L, 18656L, 18659L, 18660L, 18661L, 18662L, 18663L, 18666L, 18667L, 18668L, 18669L, 18670L, 18673L, 18674L, 18675L, 18676L, 18677L, 18680L, 18681L, 18682L, 18683L, 18684L, 18687L, 18688L, 18689L, 18690L, 18691L, 18694L, 18695L, 18696L, 18697L, 18698L, 18701L, 18702L, 18703L, 18704L, 18705L, 18708L, 18709L, 18710L, 18711L, 18712L, 18715L, 18716L, 18717L, 18718L, 18722L, 18723L, 18724L, 18725L, 18726L, 18729L, 18730L, 18731L, 18732L, 18733L, 18736L, 18737L, 18738L, 18739L, 18740L, 18743L, 18744L, 18745L, 18746L, 18747L, 18750L, 18751L, 18752L, 18753L, 18754L, 18757L, 18758L, 18759L, 18760L, 18761L, 18764L, 18765L, 18766L, 18767L, 18768L), class = c("IDate", "Date" ))结构(C(18631L,18632L,18633L,18634L,18635L,18638L,18638L,18639L,18640L,18640L,18641L,18642L,18642L,18645L,18645L,18646L,18646L,18647L,18648L,18648L,18648L,18649L,18646.186465665656565665,1L,,1864.1l,,1864, l,1864.l,18646.l,18644 ,, 18661L, 18662L, 18663L, 18666L, 18667L, 18668L, 18669L, 18670L, 18673L, 18674L, 18675L, 18676L, 18677L, 18680L, 18681L, 18682L, 18683L, 18684L, 18687L, 18688L, 18689L, 18690L, 18691L, 18694L, 18695L, 18696L,18697L,18698L,18701L,18702L,18703L,18704L,18705L,18705L,18708L,18709L,18710L,18710L,18711L,18712L,18712L,18715L,18715L,18716L,18716L,187717L,18722L,187222L,187222L,187222.L,187222.L,187222.L,187222.L,187222.L,18728年3月18728年,18722年1月18728年,第18716L, 18732L,18733L,18736L,18737L,18738L,18739L,18740L,18743L,18743L,18744L,18745L,18745L,18746L,18747L,18747L,18750L,18751L,18752L,18752L,18752L,18753L,187535.187535,18755,8754.18755 ,, 18767L, 18768L), class = c("IDate", "Date"))

I have tried to solve this using lubridate but could not succeed.我曾尝试使用 lubridate 解决此问题,但未能成功。 I am sure someone should be able to figure it out quickly.我相信有人应该能够很快弄清楚。

Perhaps, this helps也许,这有帮助

library(lubridate)
library(dplyr)
tibble(v1, v2 = floor_date(v1, 'month'), v3 = week(v1) - 
         week(v2) + 1) %>% 
 filter(v3 == 3) %>% 
 group_by(v2) %>% 
 slice_max(n = 1, order_by = v1) %>%
 ungroup

This depends on how you define weeks in each month as stated by @IRTFM.这取决于您如何定义每个月的周数,如@IRTFM 所述。 However, here is one attempt at this using base R taking help from the function here if d is the vector of dates.但是,如果d是日期的向量,这里是使用基础 R 从 function 那里获得帮助的一次尝试。

monthweeks <- function(x) {
  ceiling(as.numeric(format(x, "%d")) / 7)
}

d[monthweeks(d) == 3 & weekdays(d) == 'Friday']
#[1] "2021-01-15" "2021-02-19" "2021-03-19" "2021-04-16" "2021-05-21"

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

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